WebWork relies on XWork validation framework to enable the application of input validation rules to your Actions before they are executed. Validation in WebWork could be done through configuration or manually.
Manual Validation
Manual validation involves both workflow and validation interceptor where the action itself will be responsible for dealing with the validation.
Typically, this could be done through having the action implements Validatable interface (ActionSupport alaredy does that) :-
- override the validate() method and do the validation there
- adding a validate<action method name> method and do the validation there.
More information is available at Workflow Interceptor and Validation Interceptor
Configuration Based Validation
Configuration based validation is done through describing the validation to be applied through both build-in/custom validators using typically XML (*-validation.xml) though using annotation should be possible as well.
 | There is also an option for Client Side (Javascript and/or AJAX) based validation, please see Client Side Validation for more information. |
Examples
- Basic Validation
- Client Validation
- AJAX Validation
- Using Field Validators
- Using Non Field Validators
- Using Visitor Field Validator
Validators available in WebWork
 | Note
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. Examples: [validatortypes] |
- required validator
- requiredstring validator
- int validator
- date validator
- expression validator
- fieldexpression validator
- email validator
- url validator
- visitor validator
- conversion validator
- stringlength validator
- regex validator
- collection validator
Registering Validators
 | DTD for validators definition
As of WebWork 2.2.7 / XWork 1.2.4 we are able to have DTD for validators definition as follows:-
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Definition 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-definition-1.0.dtd">
|
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.
As of XWork 1.2.4 / WebWork 2.2.7 and above, validator definition are loaded in the following order, where
validators loaded latter could override those loaded previously if there have the same name :-
- default validators found in com/opensymphony/xwork/validator/validators/default.xml (always loaded)
- all validators.xml that lies in the root of the classpath (user defined)
- all *-validators.xml that lies in the root of the classpath (user defined)
Validators definition defined in *-validators.xml will override those defined in validators.xml if they
have similar names. This pattern applies to default.xml as well.
WebWork / XWork will always have the validator definition defined in
com/opensymphony/xwork/validator/validators/default.xml (which comes with xwork jar file) loaded.
This list declares all the validators that comes with WebWork.
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Definition 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-definition-1.0.dtd">
<validators>
<validator name="required" class="com.opensymphony.xwork.validator.validators.RequiredFieldValidator"/>
<validator name="requiredstring" class="com.opensymphony.xwork.validator.validators.RequiredStringValidator"/>
<validator name="int" class="com.opensymphony.xwork.validator.validators.IntRangeFieldValidator"/>
<validator name="double" class="com.opensymphony.xwork.validator.validators.DoubleRangeFieldValidator"/>
<validator name="date" class="com.opensymphony.xwork.validator.validators.DateRangeFieldValidator"/>
<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.xwork.validator.validators.EmailValidator"/>
<validator name="url" class="com.opensymphony.xwork.validator.validators.URLValidator"/>
<validator name="visitor" class="com.opensymphony.xwork.validator.validators.VisitorFieldValidator"/>
<validator name="conversion" class="com.opensymphony.xwork.validator.validators.ConversionErrorFieldValidator"/>
<validator name="stringlength" class="com.opensymphony.xwork.validator.validators.StringLengthFieldValidator"/>
<validator name="regex" class="com.opensymphony.xwork.validator.validators.RegexFieldValidator"/>
<validator name="collection" class="com.opensymphony.xwork.validator.validators.CollectionFieldValidator" />
</validators>
 | Note
Normally, to have custom validators, we could have them defined in validators.xml that resides in
the classpath. However since, WebWork 2.2.7 / XWork 1.2.4 and above, we could have *-validators.xml
that lies in the root of the classpath and WebWork / XWork will pick it up. This allows us to have
various validator definition that lies in a jar file itself (at the root of course).
To override a validator definition defined by XWork, we could just define a a custom validator mean
to replace it with the same name and have them in either validators.xml or *-validators.xml that lies
in the root of the classpath (could be in the root of a jar file as well).
See ValidatorFactory static block for details.
|
Turning on Validation
The default validationWorkflowStack already includes this.
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.
 | Workflow Interceptor Required
The Workflow interceptor must also be below the validation interceptor in your stack for validation to prevent action invocation. |
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 whereever 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/WebWork
is ExpressionValidator.
Notes
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.
Defining Validation Rules
Validation rules can be specified:
- Per Action class: in a file named ActionName-validation.xml
- Per Action alias: in a file named ActionName-alias-validation.xml
- 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
Here is an example for SimpleAction-validation.xml:
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.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="bar2">
<field-validator type="regex">
<param name="regex">[0-9],[0-9]</param>
<message>The value of bar2 must be in the format "x, y", where x and y are between 0 and 9</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 lt 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.
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.
bar must be between ${min} and ${max}, current value is ${bar}.
To define validation rules for an Action, create a file named ActionName-validation.xml
in the same package as the Action. You may also create alias-specific validation rules which
add to the default validation rules defined in ActionName-validation.xml by creating
another file in the same directory named ActionName-aliasName-validation.xml. In both
cases, ActionName is the name of the Action class, and aliasName is the name of the
Action alias defined in the xwork.xml configuration for the Action.
The framework will also search up the inheritance tree of the Action to
find validation rules for directly implemented interfaces and parent classes of the Action.
This is particularly powerful when combined with ModelDriven Actions and the VisitorFieldValidator.
Here's an example of how validation rules are discovered. Given the following class structure:
- interface Animal;
- interface Quadraped extends Animal;
- class AnimalImpl implements Animal;
- class QuadrapedImpl extends AnimalImpl implements Quadraped;
- class Dog extends QuadrapedImpl;
The framework method will look for the following config files if Dog is to be validated:
- Animal
- Animal-aliasname
- AnimalImpl
- AnimalImpl-aliasname
- Quadraped
- Quadraped-aliasname
- QuadrapedImpl
- QuadrapedImpl-aliasname
- Dog
- Dog-aliasname
While this process is similar to what the XW:Localization framework does
when finding messages, there are some subtle differences. The most important
difference is that validation rules are discovered from the parent downwards.
NOTE:Child's *-validation.xml will override parent's *-validation.xml
according to the class hierarchi defined above.
Validator Flavour
The validators supplied by the Xwork distribution (and any validators you
might write yourself) come in two different flavors:
- Plain Validators / Non-Field validators
- FieldValidators
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
syntax described below.)
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 " vs.
syntax" below).
There are two places where the differences between the two validator flavors
are important to keep in mind:
- when choosing the xml syntax used for declaring a validator
(either or )
- when using the short-circuit capability
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 WebWork 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.
Non-Field Validator Vs Field-Validator
There are two ways you can define validators in your -validation.xml file:
- <validator>
- <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).
syntax: -->
<validator type="expression>
<param name="expression">foo gt bar</param>
<message>foo must be great than bar.</message>
</validator>
syntax; -->
<validator type="required">
<param name="fieldName">bar</param>
<message>You must enter a value for bar.</message>
</validator>
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>.
HINT:
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:
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:
<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>
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:
<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-Curcuiting Validator
Beginning with XWork 1.0.1 (bundled with WebWork 2.1), 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
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<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 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>
<validator type="expression">
<param name="expression">email.equals(email2)</param>
<message>Email not the same as email2</message>
</validator>
<validator type="expression" short-circuit="true">
<param name="expression">email.startsWith('mark')</param>
<message>Email does not start with mark</message>
</validator>
</validators>
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:
- Plain Validator 1
- Plain Validator 2
- Field Validators for email field
- Field Validators for email2 field
Since Field 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 complecated 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 validator takes precedence over field validator meaning
that they get evaluated in the order they are defined before field validator
gets a chance to be evaludated again according to their order defined.
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 or
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>
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.
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
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
Internationalizing (i18n) validation messages
Validator's validation messages could be internatinalized. For example,
<field-validator type="required">
<message key="required.field" />
</field-validator>
or
<validator type="expression">
<param name="expression">email.startsWith('Mark')</param>
<message key="email.invalid" />
</validator>
In the first case, WebWork would look for i18n with key 'required.field' as the validation error message if
validation fails, and 'email.invalid' in the second case.
We could also provide a default message such that if validation failed and the i18n key for the message
cannot be found, WebWork would fall back and use the default message. An example would be as follows :-
<field-validator type="required">
<message key="required.field">This field is required.</message>
</field-validator>
or
<validator type="expression">
<param name="expression">email.startsWith('Mark')</param>
<message key="email.invalid">Email needs with starts with Mark</message>
</validator>
If we have an i18n message that looks something like
Hi {0}, your name must have {1} and {2}. Please try again.
and our action have getter/setter for property 'username', we could parameterized the
i18n message as follows :-
<validator type="requiredstring">
<message key="name.invalid">
<param name="0">username</param>
<param name="1">'characters'</param>
<param name="2">'numbers'</param>
</message>
</validator>
Resulting in error message like 'Hi Toby, you must have characters and numbers. Please try again.', assuming
that 'username' property is assinged with value 'Toby'. If we want to have a default message, we could do :-
<validator type="requiredstring">
<message key="name.invalid">
<param name="0">username</param>
<param name="1">'characters'</param>
<param name="2">'numbers'</param>
<param name="defaultMessage">This is the default message.</param>
</message>
</validator>
NOTE:
The i18n parameters must be numeric, eg. 0, 1, 2, 3 and they will be used in that order as well. The i18n
parameter value will be parsed as OGNL expression, hence it will be able to access our action's property as
shown in the example above.
To allow such usage, defining <param> inside <message< xml tag, we need to use the following dtd, by declaring the doctype as follows:
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Definition 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-definition-1.0.dtd">