Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migration of unmigrated content due to installation of a new plugin

Struts 2 validation is configured via XML or annotations. Manual validation in the action is also possible, and may be combined with XML and annotation-driven validation.

Validation also depends on both the validation and workflow interceptors (both are included in the default interceptor stack). The validation interceptor does the validation itself and creates a list of field-specific errors. The workflow interceptor checks for the presence of validation errors: if any are found, it returns the "input" result (by default), taking the user back to the form which contained the validation errors.

If we're using the default settings and our action doesn't have an "input" result defined and there are validation (or, incidentally, type conversion) errors, we'll get an error message back telling us there's no "input" result defined for the action.

CONTENTS

2truenone

Using Annotations

Annotations can be used as an alternative to XML for validation.

 

Bean Validation

With struts 2.5 comes the Bean Validation Plugin. That is an alternative to the classic struts validation described here. See the Plugin Page for details.

Examples

In all examples given here, the validation message displayed is given in plain English - to internationalize the message, put the string in a properties file and use a property key instead, specified by the 'key' attribute. It will be looked up by the framework (see Localization).

  1. Basic Validation
  2. Client-side Validation
  3. AJAX Validation
  4. Using Field Validators
  5. Using Non Field Validators
  6. Using Visitor Field Validator
  7. How do we repopulate controls when validation fails (FAQ entry)

Bundled Validators

...

When using a Field Validator, Field Validator Syntax is ALWAYS preferable than using the Plain Validator Syntax as it facilitates grouping of field-validators according to fields. This is very handy especially if a field needs to have many field-validators which is almost always the case.

  1. conversion validator
  2. date validator
  3. double validator
  4. email validator
  5. expression validator
  6. fieldexpression validator
  7. int validator
  8. regex validator
  9. required validator
  10. requiredstring validator
  11. short validator
  12. stringlength validator
  13. url validator
  14. visitor validator
  15. conditionalvisitor validator

Registering Validators

{snippet:id=javadoc|javadoc=true|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}The following list shows the default validators included in the framework and is an example of the syntax used to declare our own validators.{snippet:lang=xml|url=struts2/core/src/main/resources/com/opensymphony/xwork2/validator/validators/default.xml}

...

The validators.xml used to reference a DTD hosted by Opensymphony, the original location of the XWork project. Since the the move to Apache Struts, DTDs were changed. Please ensure in your projects to include the DTD header as described in the examples found here

...

The validators.xml containing custom validators needs to contain a copy of the default validators. No DTD was used in validators.xml. See: http://struts.apache.org/2.x/docs/release-notes-208.html#ReleaseNotes2.0.8-MigrationfrompreviousReleases

Turning on Validation

The default interceptor stack, "defaultStack", already has validation turned on. When creating your own interceptor-stack be sure to include both the validation and workflow interceptors. From struts-default.xml:

...

Beginning with version 2.0.4 Struts provides an extension to XWork's com.opensymphony.xwork2.validator.ValidationInterceptor interceptor.

...

This interceptor allows us to turn off validation for a specific method by using the @org.apache.struts2.interceptor.validation.SkipValidation annotation on the action method.

Validator Scopes

{snippet:id=fieldValidators|javadoc=true|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}{snippet:id=nonFieldValidators|javadoc=true|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}

Notes

{snippet:id=validatorsNote|javadoc=true|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}

Defining Validation Rules

{snippet:id=validationRules1|javadoc=true|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}{snippet:id=exValidationRules1|lang=xml|javadoc=true|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}{snippet:id=validationRules2|javadoc=true|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}

...

In this context, "Action Alias" refers to the action name as given in the Struts configuration. Often, the name attribute matches the method name, but they may also differ.

Localizing and Parameterizing Messages

{snippet:id=validationRules3|javadoc=true|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}{snippet:id=exValidationRules3|javadoc=true|lang=xml|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}{snippet:id=validationRules4|javadoc=true|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}{snippet:id=exValidationRules4|javadoc=true|lang=xml|url=com.opensymphony.xwork2.validator/ValidatorFactory.java}

Validator Flavor

{snippet:id=validatorFlavours|javadoc=true|url=com.opensymphony.xwork2.validator/Validator.java}

Non-Field Validator Vs Field-Validator validatortypes

There are two ways you can define validators in your -validation.xml file:

  1. <validator>
  2. <field-validator>

Keep the following in mind when using either syntax:

Non-Field-Validator: The <validator> element allows you to declare both types of validators (either a plain Validator a field-specific FieldValidator).

...

field-validator: The <field-validator> elements are basically the same as the <validator> elements except that they inherit the fieldName attribute from the enclosing <field> element. FieldValidators defined within a <field-validator> element will have their fieldName automatically filled with the value of the parent <field> element's fieldName attribute. The reason for this structure is to conveniently group the validators for a particular field under one element, otherwise the fieldName attribute would have to be repeated, over and over, for each individual <validator>.

...

It is always better to defined field-validator inside a <field> tag instead of using a <validator> tag and supplying fieldName as its param as the xml code itself is clearer (grouping of field is clearer)

...

Note that you should only use FieldValidators (not plain Validators) within a block. A plain Validator inside a <field> will not be allowed and would generate error when parsing the xml, as it is not allowed in the defined dtd (xwork-validator-1.0.2.dtd)

Declaring a FieldValidator using the <field-validator> syntax:

...

The choice is yours. It's perfectly legal to only use elements without the elements and set the fieldName attribute for each of them. The following are effectively equal:

...

Short-Circuiting Validator

{snippet:id=shortCircuitingValidators1|javadoc=true|url=com.opensymphony.xwork2.validator/Validator.java}{snippet:id=exShortCircuitingValidators|lang=xml|javadoc=true|url=com.opensymphony.xwork2.validator/Validator.java}{snippet:id=shortCircuitingValidators2|javadoc=true|url=com.opensymphony.xwork2.validator/Validator.java}{snippet:id=scAndValidatorFlavours1|1=javadoc|javadoc=true|url=com.opensymphony.xwork2.validator/Validator.java}{snippet:id=exScAndValidatorFlavours|lang=xml|javadoc=true|url=com.opensymphony.xwork2.validator/Validator.java}{snippet:id=scAndValidatorFlavours2|1=javadoc|javadoc=true|url=com.opensymphony.xwork2.validator/Validator.java}

How Validators of an Action are Found

{snippet:id=howXworkFindsValidatorForAction|javadoc=true|url=com.opensymphony.xwork2.validator/Validator.java}

Writing custom validators

If you want to write custom validator use on of these classes as a starting point:

  • com.opensymphony.xwork2.validator.validators.ValidatorSupport
  • com.opensymphony.xwork2.validator.validators.FieldValidatorSupport
  • com.opensymphony.xwork2.validator.validators.RangeValidatorSupport
  • com.opensymphony.xwork2.validator.validators.RepopulateConversionErrorFieldValidatorSupport

Resources

WebWork Validation

Next: Localization

If you don't know already, WebWork uses XWork as its foundation, which does provide a validation framework to help you apply input validation rules to your Actions before they are executed. This section provide only enough details to help you get started but always refer to Validation Framework for more information.

Register validators

Validators must be registered with the ValidatorFactory. This may either be done programmatically, using the registerValidator(String name, Class clazz) static method of the ValidatorFactory, or by putting a file name validators.xml in the root of the classpath (/WEB-INF/classes) with a structure like this:

...


<validators>
    <validator name="required" class="com.opensymphony.xwork.validator.validators.RequiredFieldValidator"/>
    <validator name="requiredstring" class="com.opensymphony.webwork.validators.JavaScriptRequiredStringValidator"/>
    <validator name="int" class="com.opensymphony.webwork.validators.JavaScriptIntRangeFieldValidator"/>
    <validator name="date" class="com.opensymphony.webwork.validators.JavaScriptDateRangeFieldValidator"/>
    <validator name="expression" class="com.opensymphony.xwork.validator.validators.ExpressionValidator"/>
    <validator name="fieldexpression" class="com.opensymphony.xwork.validator.validators.FieldExpressionValidator"/>
    <validator name="email" class="com.opensymphony.webwork.validators.JavaScriptEmailValidator"/>
    <validator name="url" class="com.opensymphony.webwork.validators.JavaScriptURLValidator"/>
    <validator name="visitor" class="com.opensymphony.webwork.validators.JavaScriptVisitorFieldValidator"/>
    <validator name="conversion" class="com.opensymphony.xwork.validator.validators.ConversionErrorFieldValidator"/>
</validators>

Turn on Validation

All that is required to enable validation for an Action is to put the ValidationInterceptor in the interceptor refs of the action (see xwork.xml) like so:

...


<interceptor name="validator" class="com.opensymphony.xwork.validator.ValidationInterceptor"/>

Note: The default *validationWorkflowStack" already includes this.

Validation rules can be specified:

  1. Per Action class: ActionName-validation.xml
  2. Per Action alias: ActionName-alias-validation.xml
  3. Inheritance hierarchy and interfaces implemented by Action class: WebWork searches up the inheritance tree of the action to find default validations for parent classes of the Action and interfaces implemented

Specify what and how to validate

Here is an example for SimpleAction-validation.xml:

...


<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN"
        "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
    <field name="bar">
        <field-validator type="required">
            <message>You must enter a value for bar.</message>
        </field-validator>
        <field-validator type="int">
            <param name="min">6</param>
            <param name="max">10</param>
            <message>bar must be between ${min} and ${max}, current value is ${bar}.</message>
        </field-validator>
    </field>
    <field name="date">
        <field-validator type="date">
            <param name="min">12/22/2002</param>
            <param name="max">12/25/2002</param>
            <message>The date must be between 12-22-2002 and 12-25-2002.</message>
        </field-validator>
    </field>
    <field name="foo">
        <field-validator type="int">
            <param name="min">0</param>
            <param name="max">100</param>
            <message key="foo.range">Could not find foo.range!</message>
        </field-validator>
    </field>
    <validator type="expression">
        <param name="expression">foo > bar</param>
        <message>Foo must be greater than Bar. Foo = ${foo}, Bar = ${bar}.</message>
    </validator>
</validators>

Here we can see the configuration of validators for the SimpleAction class. Validators (and field-validators) must have a type attribute, which refers to a name of an Validator registered with the ValidatorFactory as above. Validator elements may also have <param> elements with name and value attributes to set arbitrary parameters into the Validator instance. See below for discussion of the message element.

Each Validator or Field-Validator element must define one message element inside the validator element body. The message element has 1 attributes, key which is not required. The body of the message tag is taken as the default message which should be added to the Action if the validator fails.

Key gives a message key to look up in the Action's ResourceBundles using getText() from LocaleAware if the Action implements that interface (as ActionSupport does). This provides for Localized messages based on the Locale of the user making the request (or whatever Locale you've set into the LocaleAware Action).

After either retrieving the message from the ResourceBundle using the Key value, or using the Default message, the current Validator is pushed onto the ValueStack, then the message is parsed for ${...} sections which are replaced with the evaluated value of the string between the ${ and }. This allows you to parameterize your messages with values from the Validator, the Action, or both. Here is an example of a parameterized message:

Code Block

bar must be between ${min} and ${max}, current value is ${bar}.

...