OverviewThe validation framework in XWork is designed to help you apply simple validation rules to your Actions before they are executed. At its core, the framework takes just about any object and a String context name for which to validate that object. This allows you to have different validation rules for the same class in different contexts. You can define default validation rules in the class-level validation file (ClassName-validation.xml), and then define validation rules which are added on top of these for a specific context (ClassName-contextName-validation.xml). The validation rules are applied in the order they are listed in the validation files and error messages are saved into the Object (if it implements ValidationAware). In the case of Action validation, which is what most XWork users will be doing, the class name is the Action class name and the context is the Action alias. Registering ValidatorsValidation rules are handled by validators, which 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 adding a file named validators.xml to the root of the classpath that contains this information. The syntax for validators.xml is: <validators> <validator name="required" class="com.opensymphony.xwork.validator.validators.RequiredFieldValidator"/> <validator name="requiredstring" class="com.opensymphony.xwork.validator.validators.RequiredStringValidator"/> <validator name="stringlength" class="com.opensymphony.xwork.validator.validators.StringLengthFieldValidator"/> <validator name="int" class="com.opensymphony.xwork.validator.validators.IntRangeFieldValidator"/> <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="regex" class="com.opensymphony.xwork.validator.validators.RegexFieldValidator"/> </validators>
Turning on ValidationThe process of applying validation rules to an Action before it is executed is handled by the ValidationInterceptor. As such, all that is required to enable validation for an Action is to declare the ValidationInterceptor in your XWork config file and add an interceptor-ref to it for your Action. See XW:Configuration for details on how to construct your XWork config file. Here's a simple example: <xwork> <package name="example"> <interceptors> <interceptor name="validator" class="com.opensymphony.xwork.validator.ValidationInterceptor"/> </interceptors> <action name="Foo" class="com.opensymphony.xwork.SimpleAction"> <param name="foo">17</param> <param name="bar">23</param> <result name="success" type="chain"> <param name="actionName">Bar</param> </result> <interceptor-ref name="validator"/> </action> </package> <xwork> Bear in mind that the ValidationInterceptor only performs validation. The Action will still be executed even if there are any validation errors. It kicks off the validation by delegating task to ActionValidatorManager. Understanding Validator flavorsThe 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 <field-validator> 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 "<validator> vs. <field-Validator> syntax" below). There are two places where the differences between the two validator flavors are important to keep in mind:
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. Defining Validation RulesTo 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:
The framework method will look for the following config files if Dog is to be validated:
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.
Syntax for Validation RulesHere is a sample config file containing validation rules for SimpleAction from the Xwork test cases: <!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 &gt; bar</param> <message>Foo must be greater than Bar. Foo = ${foo}, Bar = ${bar}.</message> </validator> </validators> All <validator> (and <field-validator>) elements must have a type attribute, which refers to a name of a Validator registered with the ValidatorFactory as described above. These elements may also have <param> elements with name and value attributes to set arbitrary parameters into the Validator instance. All <validator> (and <field-validator>) elements must also define one message subelement, which defines the message that should be added to the Action if the validator fails. By default, the message will be that contained in the body of the message tag. The message element also has one optional attribute, key, which specifies 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). When a key is specified, any text contained in the body of the message tag becomes the default message if a message cannot be found for the given key. 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. Here is an example of a parameterized message: bar must be between $\{min\} and $\{max\}, current value is $\{bar\}. This will pull the min and max parameters from the IntRangeFieldValidator and the value of bar from the Action. A more complete example of the validation rules can be found here.
<validator> vs. <field-Validator> syntaxThere are two ways you can define validators in your -validation.xml file:
Keep the following in mind when using either syntax: <validator> Declaring a plain Validator using the <validator> syntax: <validator type="expression"> <param name="expression">foo gt bar</param> <message>foo must be great than bar.</message> </validator> Declaring a FieldValidator using the <validator> syntax: <validator type="required"> <param name="fieldName">bar</param> <message>You must enter a value for bar.</message> </validator> <field-validator> 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 <validator> elements without the <field> 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>
Note that you should only use FieldValidators (not plain Validators) within a <field-validator> 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) Short-circuiting validation checksBeginning 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: <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.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> Notice that some of the <field-validator> and <validator> elements have the short-circuit attribute set to true. short-circuiting and Validator flavors In the example above, the actual execution of validator would be as follows:
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.
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-circuiting and Field Validator flavors <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 Xwork finds a validator for an action
|