|
Recipe 8.4. Validating Dependent Fields in Struts 1.2ProblemYou are using Struts 1.2 and you want to validate a field based on the value of another related field. SolutionUse the validwhen validator. The field element in the following snippet from a validation document indicates that the zipCode is valid when the following occurs:
DiscussionThe validwhen validator, available with Struts 1.2, replaces requiredif for performing cross-field validations.
As in Recipe 8.3, the Solution shows how you would set up the validation on a form where you were retrieving a user's address. If users specify a zip code, then they can omit the city and state; otherwise, if the city or state is not specified, the zip code is required. With validwhen, you can code a single expression that takes the place of multiple XML elements needed for requiredif. The validwhen validator is more powerful than requiredif, though it can be trickier to get the logic correct. With requiredif, your validation makes the assertion "this field is required if...." The validwhen validator is different in that it asserts the statement "this field is valid when..." followed by a boolean expression. The criteria that make up the expression are open-ended.
In the Solution, the validation ensures that a zip code must have a value if the city or state is null. Likewise, if the city and state aren't null, then the zip code doesn't have to be specified; it can be null. The following expression from the Solution enforces this logic: (((city != null) and (state != null)) or (*this* != null)) The *this* notation in the expression represents the value of the field being validated, the zip code. If the zip code isn't null the expression will be true regardless of the city and state values. If the city or state is null and the zip code is null, the expression evaluates to false; the zip code isn't valid. Finally, if the city and state have values, the zip code can be any value, including null. The kinds of values allowed in a validwhen expression are the following:
The Validator parses the test expression using the ANTLR parser.
The entire expression must be enclosed in parentheses. Each logical statement, such as (foo == bar), contained in the expression must be enclosed in parentheses; using an editor that matches parentheses can help. Here are some practical guidelines for crafting validwhen expressions:
See AlsoIf you are using Struts 1.1, validwhen is not available. You may be able to use the requiredif rule, discussed in Recipe 8.3. The latest documentation on the built-in pluggable validators can be found in the Struts Validator Guide available at http://struts.apache.org/userGuide/dev_validator.html. |
|