Tips on using Struts validation framework

Struts Validations Framework How to


The struts validation framework is quite straight forward to use but there are lots of little gotchas that slow down the learning process. It should take one no more than two hours to understand and use the validation framework. Here are some of pointers that help new users of the framework.


  • Enable the validator plugin in your struts-config.xml file

<plugin- classname=org.apache.struts.validator.ValidatorPlugin>

<set-property proprty=pathnames value=/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml/>

</plugin>

  • The validation of form fields, such as required/numeric fields etc, are configured in to the validation.xml file. Most tutorial cover this quite extensively so I won't repeat it here.
  • Make sure your form class extends one of the ValidatorForms and not the standard ActionForm. ie if using the dynaform then use the DynaValidatorForm. If using a ActionForm then extend the org.apache.struts.validator.ValidatorForm instead.
  • You can over-ride the validate method of the above ValidatorForm classes if you need to do custom validations and don't want to write a whole custom validator class.
  • If you want to call the overridden validate method on your form you will need to put validate=true in your action element (see below).
  • You need to put a input attribute in your struts-config.xml file for the action on which the validation is set. i.e.
<action path="/viewList" name="ListForm" type="za.co.jumpingbean.web.actions.DisplayListAction" input="/selectStatus.jsp" validate=ᅵtrueᅵ><forward name="success" path="/viewItem.jsp"/></action>
  • The error messages shown by the validators are defined in the "ApplicationResources.properties" file. These messages are reference in the "validator-rules.xml" file and contain place holders for customisation that is passed through the "validation.xml" file. The {0} place holders in the "ApplicationResources,properties" file are filled with parameters you pass through in the "validation.xml" definitions file using the arg subelement . i.e
<field property=cusotmer depends=requried>
<arg key=error.customer/></field>
  • You can override the default message entirely by using the msg subelement instead. i.e.
<field property=customer depends=required>
<msg name=required key=error.customer/>
</field>
  • The error messages like "error.customer" are usually defined in your messages.property file or other resource bundle.

  • To enable client side validation you need to change the html:form element in your form to have the attribute "onsubmit". Note Action adn FormName should be replaced with your action mapping and the name of your form bean.

<html:form action="/Action" method="post" onsubmit=return validateFormName(this)/>

Comments

I noticed you use "quiet" instead of "quite".
They've different meanings so it can be quite confusing ;)