8.3. Validating Dependent Fields in Struts 1.1
Problem
You are using Struts 1.1 and you want to validate a field based on the value of another related field.
Solution
Use the
requiredif
validator. The field element, in this snippet from
a validation.xml file, indicates that the
zipCode field is required if the
city or state field is
null:
<!-- zipCode is required if city is null or state is null -->
<field property="zipCode" depends="requiredif">
<arg key="prompt.zipCode"/>
<var>
<var-name>field[0]</var-name>
<var-value>city</var-value>
</var>
<var>
<var-name>fieldTest[0]</var-name>
<var-value>NULL</var-value>
</var>
<var>
<var-name>field[1]</var-name>
<var-value>state</var-value>
</var>
<var>
<var-name>fieldTest[1]</var-name>
<var-value>NULL</var-value>
</var>
<var>
<var-name>fieldJoin</var-name>
<var-value>OR</var-value>
</var>
</field>Discussion
The Struts Validator has always worked well for single-field
validations. Cross-field validation, that is validating two or more
dependent fields, wasn't supported by the Validator
until Struts 1.1. The requiredif validation rule
was introduced at that time to address the problem. Interestingly
enough, the requiredif rule lifespan will be
short. It is being deprecated in Struts 1.2 and is being replaced by
the validwhen rule, discussed in Recipe 8.4.
The validation shown in the Solution would be used 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; these values would ...