Validation in detail
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
The
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.
Beginning with version 2.0.4 Struts provides an extension to XWork's
This interceptor allows us to turn off validation for a specific method by using the
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-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:
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:
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 <validator> or <field-validator> syntax was used to declare the validation rule. By way of example, given this -validation.xml file:
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.
The effect of having common validators on both
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
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.
Turning on Validation
The default interceptor stack, "defaultStack", already has validation turned on. When creating your own interceptor-stack be sure to include both thevalidation and workflow interceptors. From struts-default.xml:<interceptor-stack name="defaultStack"> ... <interceptor-ref name="validation"> <param name="excludeMethods">input,back,cancel,browse</param> </interceptor-ref> <interceptor-ref name="workflow"> <param name="excludeMethods">input,back,cancel,browse</param> </interceptor-ref></interceptor-stack> |
com.opensymphony.xwork2.validator.ValidationInterceptor interceptor.<interceptor name="validation" class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/> |
@org.apache.struts2.interceptor.validation.SkipValidation annotation on the action method.Validator Scopes
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 Validator Vs Field-Validator
There are two ways you can define validators in your -validation.xml file:- <validator>
- <field-validator>
Non-Field-Validator: The <validator> element allows you to declare both types of validators (either a plain Validator a field-specific FieldValidator).
<validator type="expression> <param name="expression">foo gt bar</param> <message>foo must be great than bar.</message> </validator> |
<validator type="required"> <param name="fieldName">bar</param> <message>You must enter a value for bar.</message> </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)
<field name="email_address"> <field-validator type="required"> <message>You cannot leave the email address field empty.</message> </field-validator> <field-validator type="email"> <message>The email address you entered is not valid.</message> </field-validator> </field> |
<field name="email_address"> <field-validator type="required"> <message>You cannot leave the email address field empty.</message> </field-validator> <field-validator type="email"> <message>The email address you entered is not valid.</message> </field-validator> </field> <validator type="required"> <param name="fieldName">email_address</param> <message>You cannot leave the email address field empty.</message> </validator> <validator type="email"> <param name="fieldName">email_address</param> <message>The email address you entered is not valid.</message> </validator> |
Short-Circuiting Validator
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.<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd"><validators> <!-- Field Validators for email field --> <field name="email"> <field-validator type="required" short-circuit="true"> <message>You must enter a value for email.</message> </field-validator> <field-validator type="email" short-circuit="true"> <message>Not a valid e-mail.</message> </field-validator> </field> <!-- Field Validators for email2 field --> <field name="email2"> <field-validator type="required"> <message>You must enter a value for email2.</message> </field-validator> <field-validator type="email"> <message>Not a valid e-mail2.</message> </field-validator> </field> <!-- Plain Validator 1 --> <validator type="expression"> <param name="expression">email.equals(email2)</param> <message>Email not the same as email2</message> </validator> <!-- Plain Validator 2 --> <validator type="expression" short-circuit="true"> <param name="expression">email.startsWith('mark')</param> <message>Email does not start with mark</message> </validator></validators> |
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:
- Plain Validator 1
- Plain Validator 2
- Field Validators for email field
- Field Validators for email2 field
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 <validator> or <field-validator> syntax was used to declare the validation rule. By way of example, given this -validation.xml file:
<validator type="required" short-circuit="true"> <param name="fieldName">bar</param> <message>You must enter a value for bar.</message></validator><validator type="expression"> <param name="expression">foo gt bar</param> <message>foo must be great than bar.</message></validator> |
How Validators of an Action are Found
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
- <actionClass>-validation.xml
- <actionClass>-<actionAlias>-validation.xml
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