Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

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 city and state properties are not null (regardless of the zipCode value).

  • The zipCode is not null:

    <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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page