The Jakarta ProjectStruts Framework

Struts Validator Guide

Contributors:

  • David Winterfeldt
  • James Turner
  • Rob Leland
Struts Validator

The Struts Validator, in some form, has been available since the days of Struts 0.5. It was orignally packaged as a developer contribution. Later, the core code was moved to the Jakarta Commons and a Struts specific extension became part of Struts 1.1.

For the convenience of the many developers who have been using the Struts Validator all along, this document first overviews the core functionality and then covers the changes and new functionality added in the Struts 1.1.

Once you have configured the Validator Plug-In, so that it can load your Validator Resources you just have to extend org.apache.struts.validator.action.ValidatorForm instead of org.apache.struts.action.ActionForm. Then when the validate method is called, the action's name attribute from the struts-config.xml is used to load the validations for the current form. So the form element's name attribute in the validator-rules.xml should match action element's name attribute.

Another alternative is to use the action mapping you are currently on by extending the ValidatorActionForm instead of the ValidatorForm. The ValidatorActionForm uses the action element's path attribute from the struts-config.xml which should match the form element's name attribute in the validator-rules.xml.

Then a separate action can be defined for each page in a multi-page form and the validation rules can be associated with the action and not a page number as in the example of a multi-page form in the validator example.

Internationalization

Validation rules for forms can be grouped under a FormSet element in the validator-rules.xml file. The FormSet has language, country, and variant attributes that correspond with the java.util.Locale class. If they are not used, the FormSet will be set to the default locale. A FormSet can also have constants associated with it. On the same level as a FormSet there can be a global element which can also have constants and have validator actions that perform validations.

Note: You must declare a default FormSet without internationalization before your internationalized FormSets. This allows the Validator to fall back to the default version if no locale is found.

The default error message for a pluggable validator can be overriden with the msg element. So instead of using the msg attribute for the mask validator to generate the error message the msg attribute from the field will be used if the name of the field's name attribute matches the validator's name attribute.

The arguments for error messages can be set with the arg0-arg3 elements. If the arg0-arg3 elements' name attribute isn't set, it will become the default arg value for the different error messages constructed. If the name attribute is set, you can specify the argument for a specific pluggable validator and then this will be used for constructing the error message.


<field
    property="lastName"
    depends="required,mask">
    <msg
        name="mask"
        key="registrationForm.lastname.maskmsg"/>
    <arg0 key="registrationForm.lastname.displayname"/>
    <var>
        <var-name>mask</var-name>
        <var-value>^[a-zA-Z]*$</var-value>
    </var>
</field>

By default the arg0-arg3 elements will try to look up the key attribute in the message resources. If the resource attribute is set to false, it will pass in the value directly without retrieving the value from the message resources.

Note that as of the Struts 1.1 release, you must explicitly define your message resource in any module that is going to use the Validator, due to a problem accessing the top-level resource. This only effects applications which are using modules.


<field
    property="integer"
    depends="required,integer,intRange">
    <arg0 key="typeForm.integer.displayname"/>
    <arg1
        name="range"
        key="${var:min}"
        resource="false"/>
    <arg2
        name="range"
        key="${var:max}"
        resource="false"/>
    <var>
        <var-name>min</var-name>
        <var-value>10</var-value>
    </var>
    <var>
        <var-name>max</var-name>
        <var-value>20</var-value>
    </var>
    </field>
Constants/Variables

Global constants can be inside the global tags and FormSet/Locale constants can be created in the formset tags. Constants are currently only replaced in the Field's property attribute, the Field's var element value attribute, the Field's msg element key attribute, and Field's arg0-arg3 element's key attribute. A Field's variables can also be substituted in the arg0-arg3 elements (ex: ${var:min}). The order of replacement is FormSet/Locale constants are replaced first, Global constants second, and for the arg elements variables are replaced last.


<global>
    <constant>
        <constant-name>zip</constant-name>
        <constant-value>^\d{5}(-\d{4})?$</constant-value>
    </constant>
</global>

<field
   property="zip"
   depends="required,mask">
<arg0 key="registrationForm.zippostal.displayname"/>
<var>
 <var-name>mask</var-name>
 <var-value>${zip}</var-value>
</var>
</field>

The var element under a field can be used to store variables for use by a pluggable validator. These variables are available through the Field's getVar(String key) method.


<field
    property="integer"
    depends="required,integer,intRange">
    <arg0 key="typeForm.integer.displayname"/>
    <arg1
        name="range"
        key="${var:min}"
        resource="false"/>
    <arg2
        name="range"
        key="${var:max}"
        resource="false"/>
    <var>
        <var-name>min</var-name>
        <var-value>10</var-value>
    </var>
    <var>
        <var-name>max</var-name>
        <var-value>20</var-value>
    </var>
    </field>
Designing Complex Validations with validwhen

A frequent requirement in validation design is to validate one field against another (for example, if you have asked the user to type in a password twice for confirmation, to make sure that the values match.) In addition, there are fields in a form that may only be required if other fields have certain values. The new validwhen validation rule, which will be included into the Struts release immediately after the 1.1 release, is designed to handle these cases.

The validwhen rule takes a single var field, called test. The value of this var is a boolean expression which must be true in order for the validation to success. The values which are allowed in the expression are:

  • Single or double-quoted string literals.
  • Integer literals in decimal, hex or octal format
  • The value null which will match against either null or an empty string
  • Other fields in the form referenced by field name, such as customerAge
  • Indexed fields in the form referenced by an explicit integer, such as childLastName[2]
  • Indexed fields in the form referenced by an implicit integer, such as childLastName[], which will use the same index into the array as the index of the field being tested.
  • Properties of an indexed fields in the form referenced by an explicit or implicit integer, such as child[].lastName, which will use the same index into the array as the index of the field being tested.
  • The literal *this, which contains the value of the field currently being tested

As an example of how this would work, consider a form with fields sendNewsletter and emailAddress. The emailAddress field is only required if the sendNewsletter field is not null. You could code this using the validwhen rule as:


<field property="emailAddress" depends="validwhen">
      <arg0 key="userinfo.emailAddress.label"/>
        <var>
          <var-name>test</var-name>
          <var-value>((sendNewsletter == null) or (*this* != null))</var-value>
        </var>
      </field>

Which reads as: this field is valid if sendNewsletter is null or the field value is not null.

Here's a slightly more complicated example using indexed fields. Assume a form with a number of lines to allow the user to enter part numbers and quantities they wish to order. An array of beans of class orderLine is used to hold the entries in a property called orderLines. If you wished to verify that every line with part number also had a quantity entered, you could do it with:


    <field property="quantity" indexedListProperty="orderLines" depends="validwhen">
      <arg0 key="orderform.quantity.label"/>
        <var>
          <var-name>test</var-name>
          <var-value>((orderLines[].partNumber == null) or (*this* != null))</var-value>
        </var>
      </field>

Which reads as: This field is value if the corresponding partNumber field is null, or this field is not null.

As a final example, imagine a form where the user must enter their height in inches, and if they are under 60 inches in height, it is an error to have checked off nbaPointGuard as a career.


    <field property="nbaPointGuard" depends="validwhen">
      <arg0 key="careers.nbaPointGuard.label"/>
        <var>
          <var-name>test</var-name>
          <var-value>((heightInInches >= 60) or (*this* == null))</var-value>
        </var>
      </field>

A few quick notes on the grammer.

  • All comparisons must be enclosed in parens.
  • Only two items may be joined with and or or
  • If both items to be compared are convertable to ints, a numeric comparison is done, otherwise a string comparison is done.
Pluggable Validators

Validation actions are read from the validation.xml file. The default actions are setup in the validation.xml file. The ones currently configured are required, mask ,byte, short, int, long, float, double, date (without locale support), and a numeric range.

The 'mask' action depends on required in the default setup. That means that 'required' has to successfully completed before 'mask' will run. The 'required' and 'mask' action are partially built into the framework. Any field that isn't 'required' will skip other actions if the field is null or has a length of zero.

If the Javascript Tag is used, the client side Javascript generation looks for a value in the validator's javascript attribute and generates an object that the supplied method can use to validate the form. For a more detailed explanation of how the Javascript Validator Tag works, see the html taglib API reference.

The 'mask' action lets you validate a regular expression mask to the field. It uses the Regular Expression Package from the jakarta site. All validation rules can be stored in the validator-rules.xml file. The main class used is org.apache.regexp.RE.

Example Validator Configuration from validation.xml.


<validator name="required"
        classname="org.apache.struts.validator.FieldChecks"
        method="validateRequired"
        methodParams="java.lang.Object,
                 org.apache.commons.validator.ValidatorAction,
                 org.apache.commons.validator.Field,
                 org.apache.struts.action.ActionErrors,
                 javax.servlet.http.HttpServletRequest"
        msg="errors.required">

<validator name="mask"
        classname="org.apache.struts.validator.FieldChecks"
        method="validateMask"
        methodParams="java.lang.Object,
                 org.apache.commons.validator.ValidatorAction,
                 org.apache.commons.validator.Field,
                 org.apache.struts.action.ActionErrors,
                 javax.servlet.http.HttpServletRequest"
        msg="errors.invalid">

Creating Pluggable Validators

The methodParams attribute takes a comma separated list of class names. The method attribute needs to have a signature complying with the above list. The list can be comprised of any combination of the following:

  • java.lang.Object - Bean validation is being performed on.
  • org.apache.commons.validator.ValidatorAction - The current ValidatorAction being performed.
  • org.apache.commons.validator.Field - Field object being validated.
  • org.apache.struts.action.ActionErrors - The errors objects to add an ActionError to if the validation fails.
  • javax.servlet.http.HttpServletRequest - Current request object.
  • javax.servlet.ServletContext - The application's ServletContext.
  • org.apache.commons.validator.Validator - The current org.apache.commons.validator.Validator instance.
  • java.util.Locale - The Locale of the current user.

Multi Page Forms

The field element has an optional page attribute. It can be set to an integer. All validation for any field on a page less than or equal to the current page is performed server side. All validation for any field on a page equal to the current page is generated for the client side Javascript. A mutli-part form expects the page attribute to be set.


<html:hidden property="page" value="1"/>

Comparing Two Fields

This is an example of how you could compare two fields to see if they have the same value. A good example of this is when you are validating a user changing their password and there is the main password field and a confirmation field.


<validator name="twofields"
       classname="com.mysite.StrutsValidator"
       method="validateTwoFields"
       msg="errors.twofields"/>

<field property="password"
       depends="required,twofields">
          <arg0 key="typeForm.password.displayname"/>
          <var>
             <var-name>secondProperty</var-name>
             <var-value>password2</var-value>
          </var>
</field>

public static boolean validateTwoFields(
    Object bean,
    ValidatorAction va, 
    Field field,
    ActionErrors errors,
    HttpServletRequest request, 
    ServletContext application) {

    String value = ValidatorUtils.getValueAsString(
        bean, 
        field.getProperty());
    String sProperty2 = field.getVarValue("secondProperty");
    String value2 = ValidatorUtils.getValueAsString(
        bean, 
        sProperty2);

    if (!GenericValidator.isBlankOrNull(value)) {
       try {
          if (!value.equals(value2)) {
             errors.add(field.getKey(),
                Resources.getActionError(
                    application,
                    request,
                    va,
                    field));

             return false;
          }
       } catch (Exception e) {
             errors.add(field.getKey(),
                Resources.getActionError(
                    application,
                    request,
                    va,
                    field));
             return false;
       }
    }

    return true;
}
Known Bugs

Since the Struts Validator relies on the Commons Validator, problem reports and enhancement requests may be listed against either product.

Changes and deprecations

New tag attributes.

The <html:javascript> tag has new attributes defined.

Validating against the DTD in the commons-validator.jar.

The validator xml files now validates against the DTD stored in the commons-validator.jar ! Struts no longer maintains a separate dtd for validator-rules.xml and validator.xml. Additionally, commons-validator now maintains a unified validator.dtd. Change all validator.xml DTD references to:


<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_0.dtd">

Blank fields.

The default validator-rules.xml now ignores blank fields for all the basic validation types. If you require a field to be present then to your applications validator.xml field definition add "required" to the depends attribute.

New range methods.

intRange & floatRange methods in both JavaScript and Java

Conditionally required fields.

The most fundamental change is the ability to conditionally require validator fields based on the value of other fields. It allows you to define logic like "only validate this field if field X is non-null and field Y equals 'male'". The recommended way to do this will be with the validwhen rule, described above, and available in the first release after 1.1. The requiredif validation rule, which was added in Struts 1.1, will be deprecated in favor of this rule, and will be removed in a future release. However, if you are using requiredif, here is a brief tutorial.

Let's assume you have a medical information form with three fields, sex, pregnancyTest, and testResult. If sex is 'f' or 'F', pregnancyTest is required. If pregnancyTest is not blank, testResult is required. The entry in your validation.xml file would look like this:

<form name="medicalStatusForm">

<field
    property="pregnancyTest" depends="requiredif">
  <arg0 key="medicalStatusForm.pregnancyTest.label"/>
  <var>
    <var-name>field[0]</var-name>
    <var-value>sex</var-value>
  </var>
  <var>
    <var-name>fieldTest[0]</var-name>
    <var-value>EQUAL</var-value>
  </var>
  <var>
    <var-name>fieldValue[0]</var-name>
    <var-value>F</var-value>
  </var>
  <var>
    <var-name>field[1]</var-name>
    <var-value>sex</var-value>
  </var>
  <var>
    <var-name>fieldTest[1]</var-name>
    <var-value>EQUAL</var-value>
  </var>
  <var>
    <var-name>fieldValue[1]</var-name>
    <var-value>f</var-value>
  </var>
  <var>
    <var-name>fieldJoin</var-name>
    <var-value>OR</var-value>
  </var>
</field>

<field
    property="testResult" depends="requiredif">
  <arg0 key="medicalStatusForm.testResult.label"/>
  <var>
    <var-name>field[0]</var-name>
    <var-value>pregnancyTest</var-value>
  </var>
  <var>
    <var-name>fieldTest[0]</var-name>
    <var-value>NOTNULL</var-value>
  </var>
</field>
</form>

Here's a more complex example using indexed properties.

If you have this in your struts-config.xml

<form-bean
    name="dependentlistForm"
    type="org.apache.struts.webapp.validator.forms.ValidatorForm">
    <form-property
        name="dependents"
        type="org.apache.struts.webapp.validator.Dependent[]" size="10"/>
    <form-property
        name="insureDependents"
        type="java.lang.Boolean"
        initial="false"/>
</form-bean>

Where dependent is a bean that has properties lastName, firstName, dob, coverageType

You can define a validation:


<form name="dependentlistForm">

<field
    property="firstName" indexedListProperty="dependents"
    depends="requiredif">
  <arg0 key="dependentlistForm.firstName.label"/>
  <var>
    <var-name>field[0]</var-name>
    <var-value>lastName</var-value>
  </var>
  <var>
    <var-name>fieldIndexed[0]</var-name>
    <var-value>true</var-value>
  </var>
  <var>
    <var-name>fieldTest[0]</var-name>
    <var-value>NOTNULL</var-value>
  </var>
</field>

<field
    property="dob"
    indexedListProperty="dependents"
    depends="requiredif,date">
  <arg0 key="dependentlistForm.dob.label"/>
  <var>
    <var-name>field[0]</var-name>
    <var-value>lastName</var-value>
  </var>
  <var>
    <var-name>fieldIndexed[0]</var-name>
    <var-value>true</var-value>
  </var>
  <var>
    <var-name>fieldTest[0]</var-name>
    <var-value>NOTNULL</var-value>
  </var>
</field>

<field
    property="coverageType"
    indexedListProperty="dependents"
    depends="requiredif">
  <arg0 key="dependentlistForm.coverageType.label"/>
  <var>
    <var-name>field[0]</var-name>
    <var-value>lastName</var-value>
  </var>
  <var>
    <var-name>fieldIndexed[0]</var-name>
    <var-value>true</var-value>
  </var>
  <var>
    <var-name>fieldTest[0]</var-name>
    <var-value>NOTNULL</var-value>
  </var>
  <var>
    <var-name>field[1]</var-name>
    <var-value>insureDependents</var-value>
  </var>
  <var>
    <var-name>fieldTest[1]</var-name>
    <var-value>EQUAL</var-value>
  </var>
  <var>
    <var-name>fieldValue[1]</var-name>
    <var-value>true</var-value>
  </var>
  <var>
    <var-name>fieldJoin</var-name>
    <var-value>AND</var-value>
  </var>
</field>

</form>

Which is read as follows: The firstName field is only required if the lastName field is non-null. Since fieldIndexed is true, it means that lastName must be a property of the same indexed field as firstName. Same thing for dob, except that we validate for date if not blank.

The coverageType is only required if the lastName for the same indexed bean is not null, and also if the non-indexed field insureDependents is true.

You can have an arbitrary number of fields by using the [n] syntax, the only restriction is that they must all be AND or OR, you can't mix.

Deprecations.

  • Deprecation of range methods in both JavaScript and Java.
  • Deprecation of StrutsValidator & StrutsValidatorUtil.
Validator API Guide

A concise Struts Validator API Guide is available to help you get started.

Validator Resources

Struts Validator: Validating Two Fields Match by Matt Raible. Howto article.

DynaForms and the Validator by James Turner and Kevin Bedell. Sample chapter from Struts Kickstart; available as a free download (PDF).

Validating user input by David Winterfeldt and Ted Husted. Sample chapter from Struts in Action; available as a free download (PDF).


Copyright (c) 2000-2003, Apache Software Foundation