Home > Guides > Core Developers Guide > Validation |
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
Annotations can be used as an alternative to XML for validation.
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).
Validation rules are handled by validators, which must be registered with the ValidatorFactory (using the registerValidator method). The simplest way to do so is to add a file name validators.xml in the root of the classpath (/WEB-INF/classes) that declares all the validators you intend to use.
The following list shows the default validators included in the framework and is an example of the syntax used to declare our own validators.
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.
Field validators, as the name indicate, act on single fields accessible through an action. A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule. Most validations can be defined on per field basis. This should be preferred over non-field validation wherever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view.
Non-field validators only add action level messages. Non-field validators are mostly domain specific and therefore offer custom implementations. The most important standard non-field validator provided by XWork is ExpressionValidator.
Non-field validators takes precedence over field validators regardless of the order they are defined in *-validation.xml. If a non-field validator is short-circuited, it will causes its non-field validator to not being executed. See validation framework documentation for more info.
Validation rules can be specified:
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.
If the validator fails, the validator is pushed onto the ValueStack and the message - either the default or the locale-specific one if the key attribute is defined (and such a message exists) - 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.
NOTE: Since validation rules are in an XML file, you must make sure you escape special characters. For example, notice that in the expression validator rule above we use ">" instead of ">". Consult a resource on XML for the full list of characters that must be escaped. The most commonly used characters that must be escaped are: & (use &, > (user >, and < (use <.
Here is an example of a parameterized message:
This will pull the min and max parameters from the IntRangeFieldValidator and the value of bar from the Action.
Another notable fact is that the provided message value is capable of containing OGNL expressions. Keeping this in mind, it is possible to construct quite sophisticated messages.
See the following example to get an impression:
The validators supplied by the XWork distribution (and any validators you might write yourself) come in two different flavors:
Plain Validators (such as the ExpressionValidator) perform validation checks
that are not inherently tied to a single specified field. When you declare a
plain Validator in your -validation.xml file you do not associate a fieldname
attribute with it. (You should avoid using plain Validators within the
FieldValidators (such as the EmailValidator) are designed to perform
validation checks on a single field. They require that you specify a fieldname
attribute in your -validation.xml file. There are two different (but equivalent)
XML syntaxes you can use to declare FieldValidators (see "
There are two places where the differences between the two validator flavors are important to keep in mind:
NOTE:Note that you do not declare what "flavor" of validator you are using in your -validation.xml file, you just declare the name of the validator to use and Struts will know whether it's a "plain Validator" or a "FieldValidator" by looking at the validation class that the validator's programmer chose to implement.
There are two ways you can define validators in your -validation.xml file:
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>.
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:
It is possible to short-circuit a stack of validators. Here is another sample config file containing validation rules from the Xwork test cases: Notice that some of the <field-validator> and <validator> elements have the short-circuit attribute set to true.
short-circuiting and Validator flavors
Plain validator takes precedence over field-validator. They get validated first in the order they are defined and then the field-validator in the order they are defined. Failure of a particular validator marked as short-circuit will prevent the evaluation of subsequent validators and an error (action error or field error depending on the type of validator) will be added to the ValidationContext of the object being validated.
In the example above, the actual execution of validator would be as follows:
Since Plain Validator 2 is short-circuited, if its validation failed, it will causes Field validators for email field and Field validators for email2 field to not be validated as well.
Usefull Information: More complicated validation should probably be done in the validate() method on the action itself (assuming the action implements Validatable interface which ActionSupport already does).
A plain Validator (non FieldValidator) that gets short-circuited will completely break out of the validation stack. No other validators will be evaluated and plain validators takes precedence over field validators meaning that they get evaluated in the order they are defined before field validators get a chance to be evaluated.
Short cuircuiting and validator flavours
A FieldValidator that gets short-circuited will only prevent other
FieldValidators for the same field from being evaluated. Note that this
"same field" behavior applies regardless of whether the
both validators will be run, even if the "required" validator short-circuits. "required" validators are FieldValidator's and will not short-circuit the plain ExpressionValidator because FieldValidators only short-circuit other checks on that same field. Since the plain Validator is not field specific, it is not short-circuited.
As mentioned above, the framework will also search up the inheritance tree of the action to find default validations for interfaces and parent classes of the Action. If you are using the short-circuit attribute and relying on default validators higher up in the inheritance tree, make sure you don't accidentally short-circuit things higher in the tree that you really want!
The effect of having common validators on both
It should be noted that the nett effect will be validation on both the validators available in both validation configuration file. For example if we have 'requiredstring' validators defined in both validation xml file for field named 'address', we will see 2 validation error indicating that the the address cannot be empty (assuming validation failed). This is due to WebWork will merge validators found in both validation configuration files.
The logic behind this design decision is such that we could have common validators in <actionClass>-validation.xml and more context specific validators to be located in <actionClass>-<actionAlias>-validation.xml