8.4. Validating Dependent Fields in Struts 1.2
Problem
You are using Struts 1.2 and you want to validate a field based on the value of another related field.
Solution
Use the
validwhen
validator. The field element in the following
snippet from a validation document indicates
that the zipCode is valid when the following
occurs:
The
cityandstateproperties are notnull(regardless of thezipCodevalue).The
zipCodeis notnull:<form name="AddressForm"> <field property="zipCode" depends="validwhen"> <arg key="prompt.zipCode"/> <var> <var-name> test </var-name> <var-value> (((city != null) and (state != null)) or (*this* != null)) </var-value> </var> </field> <form name="AddressForm">
Discussion
The
validwhen
validator, available with Struts 1.2, replaces
requiredif for performing cross-field validations.
Warning
The validwhen validator, like
requiredif, can't be used for
client-side validation, only server-side validation.
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 ...