Creating Custom Validations


Using Validator

Using the Validator framework involves enabling the Validator plugin, configuring Validator's two configuration files, and creating Form Beans that extend Validator's ActionForm subclasses. The following sections explain how to configure and use the Validator in detail.

Note 

Detailed information on configuring the Validator XML configuration files is found in Chapter 20.

Enabling the Validator Plugin

Although the Validator framework comes packaged with Struts, by default Validator is not enabled. In order to enable and use Validator, you have to add to your application's Struts configuration file the following definition for the plug-in tag:

<!-- Validator Configuration --> <plug-in className="org.apache.struts.validator.ValidatorPlugIn">   <set-property property="pathnames"                    value="/org/apache/struts/validator/validator-rules.xml,                           /WEB-INF/validation.xml"/> </plug-in> 

This definition causes Struts to load and initialize the Validator plugin for your application. Upon initialization, the plugin loads the comma-delimited list of Validator configuration files specified by the pathnames property. Each configuration file's path must be specified by using a Web application–relative path or by using a path to a file on the classpath of the server, as shown in the preceding example. The validator-rules.xml file shown in the preceding example happens to be stored in the core Struts .jar file, and thus it is accessible via the classpath.

Note that your application's Struts configuration file must conform to the Struts Configuration DTD, which specifies the order in which elements are to appear in the file. Because of this, you must place the Validator plug-in tag definition in the proper place in the file. The easiest way to ensure that you are properly ordering elements in the file is to use a tool like Struts Console that automatically formats your configuration file so that it conforms to the DTD.

Creating Form Beans

In order to use Validator, your application's Form Beans must subclass one of Validator's ActionForm subclasses instead of ActionForm itself. Validator's ActionForm subclasses provide an implementation for ActionForm's reset( ) and validate( ) methods that hook into the Validator framework. Instead of hard-coding validations into the validate( ) method, as you would normally do, you simply omit the method altogether because Validator provides the validation code for you.

Parallel to the core functionality provided by Struts, Validator gives you two options to choose from when creating Form Beans. The first option is to create a concrete Form Bean object like the one shown here:

package com.jamesholmes.minihr;     import org.apache.struts.validator.ValidatorForm;     public class LogonForm extends ValidatorForm {   private String username;   private String password;       public String getUsername() {     return username;   }       public void setUsername(String username) {     this.username = username;   }       public String getPassword() {     return password;   }       public void setPassword(String password) {     this.password = password;   } } 

This class is similar to one that you would create if you were not using Validator; however, this class extends ValidatorForm instead of ActionForm. This class also does not provide an implementation for ActionForm's empty reset( ) and validate( ) methods, because ValidatorForm does.

You configure this Form Bean in the Struts configuration file the same way you would a regular Form Bean, as shown here:

<form-beans>   <form-bean name="logonForm"              type="com.jamesholmes.minihr.LogonForm"/> </form-beans>

The logical name given to the Form Bean with the form-bean tag's name attribute is the name that you will use when defining validations in the validation.xml file, as shown here:

<!DOCTYPE form-validation PUBLIC           "-//Apache Software Foundation//DTD Commons            Validator Rules Configuration 1.3.0//EN"           "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">     <form-validation>   <formset>     <form name="logonForm">       <field property="username" depends="required">         <arg position="0" key="prompt.username"/>       </field>     </form>   </formset> </form-validation>

Validator uses the value of the form tag's name attribute to match validation definitions to the name of the Form Bean to which they are applied.

The second option you can choose when creating your Form Bean is to define a Dynamic Form Bean in the Struts configuration file, as shown here:

<form-beans>   <form-bean name="logonForm"              type="org.apache.struts.validator.DynaValidatorForm">     <form-property name="username" type="java.lang.String"/>     <form-property name="password" type="java.lang.String"/>   </form-bean> </form-beans>

Dynamic Form Beans do not require you to create concrete Form Bean objects; instead, you define the properties that your Form Bean will have and their types, and Struts will dynamically create the Form Bean for you. Validator allows you to use this concept just as you would with core Struts. The only difference for Validator is that you specify that your Form Bean is of type org.apache.struts.validator.DynaValidatorForm instead of org.apache.struts.action.DynaActionForm.

Identical to the way concrete Form Beans work with Validator, the logical name given to Dynamic Form Beans is the name that you will use when defining validations in the validation.xml file. Validator uses the matching names to tie the validations to the Form Bean.

In addition to the two standard options for creating Form Beans, Validator provides an advanced feature for tying multiple validation definitions to one Form Bean definition. When using ValidatorForm- or DynaValidatorForm-based Form Beans, Validator uses the logical name for the Form Bean from the Struts configuration file to map the Form Bean to validation definitions in the validation.xml file. This mechanism is ideal for most cases; however, there are scenarios where Form Beans are shared among multiple actions. One action may use all the Form Bean's fields, and another action may use only a subset of the fields. Because validation definitions are tied to the Form Bean, the action that uses only a subset of the fields has no way of bypassing validations for the unused fields. When the Form Bean is validated, it will generate error messages for the unused fields because Validator has no way of knowing not to validate the unused fields; it simply sees them as missing or invalid.

To solve this problem, Validator provides two additional ActionForm subclasses that allow you to tie validations to actions instead of Form Beans. That way you can specify which validations to apply to the Form Bean based on which action is using the Form Bean. For concrete Form Beans, you subclass org.apache.struts.validator.ValidatorActionForm, as shown here:

public class AddressForm extends ValidatorActionForm {   ... }

For Dynamic Form Beans, you specify a type of org.apache.struts.validator. DynaValidatorActionForm for your Form Bean definition in the Struts configuration file:

<form-bean name="addressForm"            type="org.apache.struts.validator.DynaValidatorActionForm">   ... </form-bean>

Inside your validation.xml file, you map a set of validations to an action path instead of to a Form Bean name. Here's why: if you have two actions defined, such as Create Address and Edit Address, which use the same Form Bean, then each will have a unique action path. This situation is shown here:

<action-mappings>   <action path="/createAddress"           type="com.jamesholmes.minihr.CreateAddressAction"           name="addressForm"/>   <action path="/editAddress"           type="com.jamesholmes.minihr.EditAddressAction"           name="addressForm"/> </action-mappings>

The following validation.xml file snippet shows two sets of validations that are intended for the same Form Bean but are distinguished by different action paths:

<formset>   <form name="/createAddress">     <field property="city" depends="required">       <arg position="0" key="prompt.city"/>     </field>   </form>   <form name="/editAddress">     <field property="state" depends="required">       <arg position="0" key="prompt.state"/>     </field>   </form> </formset>

Because your Form Bean subclasses either ValidatorActionForm or DynaValidatorActionForm, Validator knows to use an action path to find validations instead of the Form Bean's logical name.

Using Validator in Conjunction with the Form Bean's reset( ) and validate( ) Methods

As described, Validator's ActionForm subclasses take care of the processing that is normally placed in the reset( ) and validate( ) methods of a Form Bean. Thus, you typically do not have an implementation of these two methods in your Form Beans when using Validator. However, it is occasionally necessary to augment the automatic processing provided by Validator with your own custom validations or data resets. To do this, you must override the reset( ) and/or validate( ) methods provided by the Validator Form Bean classes and call super.reset( ) and super.validate( ) respectively before adding any custom processing to the methods. An example of this is shown next:

public void reset(ActionMapping mapping,                   HttpServletRequest request) {   super.reset(mapping, request);       // Custom reset code goes here. }     public ActionErrors validate(ActionMapping mapping,                              HttpServletRequest request) {   ActionErrors errors = super.validate(mapping, request);   if (errors == null) {     errors = new ActionErrors();   }       // Custom validation code goes here.       return errors; }

Notice that the call to super.validate( ) in the validate( ) method returns an ActionErrors instance. Errors generated from custom validations should be added to that ActionErrors instance and that instance should be used as the method's return value.

Configuring validator-rules.xml

The Validator framework is set up as a pluggable system whereby each of its validation routines is simply a Java method that is plugged into the system to perform a specific validation. The validator-rules.xml file is used to declaratively plug in the validation routines that Validator will use for performing validations. Struts comes packaged with a preconfigured copy of this file in the Struts core .jar file (e.g., struts-core-1.3.5.jar). Under most circumstances, you will use this preconfigured copy and will not ever need to modify it. Modification to the file would require extracting it from the core .jar file, making changes to the file and then repackaging the core .jar file with the modified file. As you can imagine, that is cumbersome and should only be done if absolutely necessary. Otherwise you can simply add validation routine definitions to the validation.xml file as explained in the section "Creating Custom Validations."

Following is a sample validator-rules.xml file that illustrates how validation routines are plugged into Validator:

<!DOCTYPE form-validation PUBLIC           "-//Apache Software Foundation//DTD Commons            Validator Rules Configuration 1.3.0//EN"           "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">         <form-validation>   <global>     <validator name="minlength"           classname="org.apache.struts.validator.FieldChecks"              method="validateMinLength"        methodParams="java.lang.Object,                      org.apache.commons.validator.ValidatorAction,                      org.apache.commons.validator.Field,                      org.apache.struts.action.ActionMessages,                      org.apache.commons.validator.Validator,                      javax.servlet.http.HttpServletRequest"                 msg="errors.minlength"          jsFunction="org.apache.commons.validator.javascript.validateMinLength"/>   </global> </form-validation>

Each validation routine in the validator-rules.xml file has its own definition that is declared with a validator tag. The validator tag is used to assign a logical name to the routine, with the name attribute, and to specify the class and method for the routine. The logical name given to the routine will be used to refer to the routine by other routines in this file as well as by validation definitions in the validation.xml file.

Notice that the validator tag specifies a msg attribute. The msg attribute specifies a key for a message in the application resource bundle file that will be used as the error message when the validation fails. Notice also that the validator tag specifies a jsFunction attribute. The jsFunction attribute is used to define the path to a file that contains client-side JavaScript code for the validation routine. The JavaScript code performs the same validation on the client side as is performed on the server side.

Note 

In lieu of using the jsFunction attribute of the validator tag to declare the file in which the routine's client-side JavaScript code is housed, you can nest a javascript tag beneath the validator tag to specify the JavaScript code for a validation routine.

Configuring the Application Resource Bundle File

Validator uses the Struts Resource Bundle mechanism for externalizing error messages. Instead of having hard-coded error messages in the framework, Validator allows you to specify a key to a message in the application resource bundle file (e.g., MessageResources. properties) that is returned if a validation fails. Each validation routine in the validator-rules. xml file specifies an error message key with the validator tag's msg attribute, as shown here:

<validator name="minlength"       classname="org.apache.struts.validator.FieldChecks"          method="validateMinLength"    methodParams="java.lang.Object,                  org.apache.commons.validator.ValidatorAction,                  org.apache.commons.validator.Field,                  org.apache.struts.action.ActionMessages,                  org.apache.commons.validator.Validator,                  javax.servlet.http.HttpServletRequest"             msg="errors.minlength"      jsfunction="org.apache.commons.validator.javascript.validateMinLength"/>

If the validation fails when it is run, the message corresponding to the key specified by the msg attribute will be returned.

The following snippet shows the default set of validation error messages from the MessageResources.properties file that comes prepackaged with the Struts example applications. Each message key corresponds to those specified by the validation routines in the validator-rules.xml file that also comes prepackaged with the Struts example applications:

# Error messages for Validator framework validations errors.required={0} is required. errors.minlength={0} cannot be less than {1} characters. errors.maxlength={0} cannot be greater than {1} characters. errors.invalid={0} is invalid. errors.byte={0} must be a byte. errors.short={0} must be a short. errors.integer={0} must be an integer. errors.long={0} must be a long. errors.float={0} must be a float. errors.double={0} must be a double. errors.date={0} is not a date. errors.range={0} is not in the range {1} through {2}. errors.creditcard={0} is not a valid credit card number. errors.email={0} is an invalid e-mail address. errors.url={0} is an invalid URL.

Notice that each message has placeholders in the form of {0}, {1}, or {2}. At run time, the placeholders will be substituted for another value, such as the name of the field being validated. This feature is known as parametric replacement and is especially useful in allowing you to create generic validation error messages that can be reused for several different fields of the same type.

Take for example the required validation's error message, errors.required:

errors.required={0} is required.

When you use the required validation in the validation.xml file, you have to define the value that should be used to substitute {0} in the error message:

<form name="auctionForm">   <field property="bid" depends="required">     <arg position="0" key="prompt.bid"/>   </field> </form> 

Error messages can have multiple placeholders: {0} – {N}. These placeholders are specified using the arg tag. In the preceding example, the arg tag specifies the value that will replace the {0} placeholder. This tag's key attribute specifies a message key from the application resource bundle file, such as the one shown next, whose value will be used as the replacement for the placeholder:

prompt.bid=Auction Bid

Using a message key for the placeholder value frees you from having to hard-code the replacement value over and over in the validation.xml file. However, if you don't want to use the Resource Bundle key/value mechanism to specify placeholder values, you can explicitly specify the placeholder value by using the following syntax for the arg tag:

<arg position="0" key="Auction Bid" resource="false"/>

In this example, the resource attribute is set to false, instructing Validator that the value specified with the key attribute should be taken as the literal placeholder value and not as a key for a message in the application resource bundle file.

Configuring validation.xml

The validation.xml file is used to declare sets of validations that should be applied to Form Beans. Each Form Bean that you want to validate has its own definition in this file. Inside that definition specify the validations that you want to apply to the Form Bean's fields. Following is a sample validation.xml file that illustrates how validations are defined:

<!DOCTYPE form-validation PUBLIC           "-//Apache Software Foundation//DTD Commons            Validator Rules Configuration 1.3.0//EN"           "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">     <form-validation>   <formset>     <form name="logonForm">       <field property="username" depends="required">         <arg position="0" key="prompt.username"/>       </field>       <field property="password" depends="required">         <arg position="0" key="prompt.password"/>       </field>     </form>   </formset> </form-validation>

The first element in the validation.xml file is the <form-validation> element. This element is the master element for the file and is defined only once. Inside the <form-validation> element you define <form-set> elements that encapsulate multiple <form> elements. Generally, you will define only one <form-set> element in your file; however, you would use a separate one for each locale if you were internationalizing validations. Internationalizing validations is covered later in this chapter.

Each <form> element uses the name attribute to associate a name with the set of field validations it encompasses. Validator uses this logical name to map the validations to a Form Bean defined in the Struts configuration file. Based on the type of Form Bean being validated, Validator will attempt to match the name either against a Form Bean's logical name or against an action's path. Inside the <form> element, <field> elements are used to define the validations that will be applied to specified Form Bean fields. The <field> element's property attribute corresponds to the name of a field in the specified Form Bean. The depends attribute specifies the logical names of validation routines from the validatorrules.xml file that should be applied to the field. The validations specified with the depends attribute will be performed in the order specified and they all must pass.

Working with Configurable Validations

Each of the prepackaged validations provided by Validator requires configuring before it will function properly. There are two types of configuration constructs that validations can use: error message parametric replacement definitions and variable definitions. Error message parametric replacement definitions are defined with the arg tag and specify values for placeholders in the error message associated with a validation. Before an error message is generated for a failed validation, the message's placeholders are replaced with the values specified with arg tags. Variable definitions are defined with the var tag and specify validation-specific configuration settings. Validations use the configuration settings specified with var tags to guide their behavior.

Following is an example of how to use the arg tag to specify a parametric replacement value for a validation's error message:

<field property="password" depends="required, minlength">   <arg position="0" key="prompt.password"/> </field>

The position attribute of the arg tag is used to specify which parameter will be replaced with the given value. For example, position "0" is used to replace "{0}" in a message, position "1" is used to replace "{1}" and so on. An example error message with a replacement placeholder is shown here:

errors.required={0} is required.

The key attribute of the arg tag specifies a key for a value in the application resource bundle file that will be used to populate the validation's error message. Alternatively, you can set the resource attribute of the arg tag to "false" to indicate that the value specified with the key attribute should be taken as the literal replacement value instead of as the key for a value in the resource bundle. An example of specifying a literal replacement value is shown next:

<field property="password" depends="required, minlength">   <arg position="0" key="Password" resource="false"/> </field>

The value "Password" will be used to replace the "{0}" in the validations' error messages.

Each validation applied to a field via the depends attribute of the field tag will use the same parametric replacement values specified with arg tags unless an arg tag explicitly specifies the validation it is to be used for with the name attribute, as shown next:

<field property="password" depends="required, minlength">   <arg position="0" name="required" key="prompt.passwordReq"/>   <arg position="0" name="minlength" key="prompt.passwordMin"/> </field>

The name attribute specifies the name of a specific validation that the parametric replacement value is for.

Next is an example of how to use the var tag to specify a configuration setting for a validation:

<field property="socialSecurityNum" depends="required, mask">   <arg position="0" key="label.sampleForm.socialSecurityNum"/>   <var>     <var-name>mask</var-name>     <var-value>^\d{3}-\d{2}-\d{4}$</var-value>   </var> </field>

Inside the var tag you must nest var-name and var-value tags to specify the name and value of a configuration setting, respectively. The names of acceptable configuration settings specified with the var-name tag are validation-specific and can be found in the sections dedicated to each validation later in this chapter. With some validations it is useful to use the value set for a variable with the var-value tag as the value for a parametric replacement in the error message. For example, the minlength validation's error message has a placeholder for minimum length. Instead of specifying the minimum length twice, once for the error message and once for the validation configuration setting, you can use the value of the configuration setting as the value for the placeholder. The example shown next illustrates how to do this:

<field property="password" depends="required, minlength">   <arg position="0" key="label.sampleForm.password"/>   <arg position="1" key="${var:minlength}" resource="false"/>   <var>     <var-name>minlength</var-name>     <var-value>4</var-value>   </var> </field>

Notice that the second arg tag's key attribute is set to "${var:minlength}" and the resource attribute is set to "false". Recall that setting the resource attribute to false indicates that the value specified with the key attribute is to be taken as a literal value instead of as a key from the application resource bundle file. The "${var:minlength}" value of the key attribute indicates that the literal value should be the value of the minlength variable defined with the var tag.

Extending a Set of Validations

As of Commons Validator version 1.2, Validator has a feature for extending form definitions. This powerful mechanism is analogous to inheritance in Java and makes setting up similar forms very simple. For example, if you have a registration form with several fields and you need to define another form that has all of the same fields as the registration form plus a few additional fields, you can simply extend the registration form and add only the additional fields to the second form's definition. Following is an example of how this is done:

<form-validation>   <formset>     <form name="registrationForm">       <field property="name" depends="required">         <arg position="0" key="prompt.name"/>       </field>       <field property="address" depends="required">         <arg position="0" key="prompt.address"/>       </field>     </form>     <form name="businessRegistrationForm" extends="registrationForm">       <field property="suite" depends="required">         <arg position="0" key="prompt.suite"/>       </field>     </form>   </formset> </form-validation>

Notice in the example that the form definition for the businessRegistrationForm uses the form tag's extends attribute to specify another form that the form extends. All of the validation configuration details from the registrationForm form definition will be added to the businessRegistrationForm form defintion. Again, as with Java's inheritance feature, you can have any number of levels of extension.

Creating Validations for Indexed Properties

As mentioned in Chapter 4, indexed properties are a powerful and convenient mechanism for working with lists of objects on form beans. Validator provides built-in support for validating indexed properties via the indexedListProperty attribute of the field tag, as shown here:

<form name="registrationForm">   <field property="firstName"       indexedListProperty="customer" depends="required">     <arg position="0" key="prompt.firstName"/>   </field>   <field property="lastName"       indexedListProperty="customer" depends="required">     <arg position="0" key="prompt.lastName"/>   </field> </form>

In this example, the registrationForm has a customer indexed property, as specified with the indexedListProperty attribute of the field tag. Validator will loop over each object in the customer indexed property and validate the field specified with the property attribute. This scenario assumes that the property specified with the indexedListProperty attribute is a collection of objects and the field specified with the property attribute has getter and setter methods on the individual objects in the collection.

Validations That Span Multiple Pages

Web applications often use wizard-like page flows to break up large monolithic forms into multiple pages to reduce the amount of information that must be entered on a single page. In that scenario, it is commonplace to use one Form Bean to store the data collected across all of the pages. At the end of the wizard page flow an action will process all of the collected data at once. The problem with that scenario, validation-wise, is that validations are specified per form in the validation.xml file and not all validations should be run against the form on each page. For example, the fields on page 2 shouldn't be validated on page 1 because they have not been entered yet. Any validations for page 2 that are run before page 2 is reached will fail. This is the case for each successive page in the wizard page flow. Validator has a feature to handle this situation so that validations are run only at the appropriate times.

In order to limit when validations are run for a form that spans multiple pages, the field tag has a page attribute that is used to specify a page number, as shown next:

<form name="registrationForm">   <field property="name" page="1" depends="required">     <arg position="0" key="prompt.name"/>   </field>   <field property="address" page="1" depends="required">     <arg position="0" key="prompt.address"/>   </field>   <field property="username" page="2" depends="required">     <arg position="0" key="prompt.username"/>   </field>   <field property="password" page="2" depends="required">     <arg position="0" key="prompt.password"/>   </field> </form>

The page number specified with the field tag's page attribute corresponds to the value of a field on the associated form bean that must be set in the JSP page:

<html:hidden property="page" value="1"/>

The page property is already on the Validator ActionForm subclasses, so you don't need to add it to your Form Beans.

Each page must use the HTML Tag Library's hidden tag to specify a unique value for the page property. When validations are run, Validator compares the page value from the form with the page value set on the field tag with the page attribute. If the values are less than or equal to one another, the validations for the given field are run. Otherwise, the field's validations are skipped. Note that if you need to apply any custom reset logic on your Form Bean's fields using the reset( ) method, you can use the page property, as shown here:

public void reset(ActionMapping mapping,                   HttpServletRequest request) {   super.reset(mapping, request);       // Custom reset code goes here.   if (page == 1) {     // Reset page 1 properties.   }   else if (page == 2) {     // Reset page 2 properties.   } }

As mentioned, the page property is a protected member of the Validator ActionForm subclasses, and thus it is available to Form Beans that extend those subclasses.

Using Validator's Included Validations

Validator, by default, includes several basic validation routines that you can use to solve most validation scenarios. As mentioned, Struts comes packaged with a preconfigured validator-rules.xml file that defines these routines. Table 6-1 lists each of the preconfigured validations by logical name and states its purpose. The following sections describe each of the preconfigured validations listed in the table, and usage examples are given.

Table 6-1: Validator's Preconfi gured Validations

Name

Description

byte

Determines whether the field being validated contains a value that can be converted to a Java byte primitive type.

byteLocale

Determines whether the field being validated contains a value that can be converted to a Java byte primitive type using the number formatting conventions of the current user's locale.

creditCard

Determines whether the field being validated contains a valid credit card number from one of the four major credit card companies (American Express, Discover, MasterCard, or Visa).

date

Determines whether the field being validated contains a value that can be converted to a java.util.Date type using the java.text.SimpleDateFormat class.

double

Determines whether the field being validated contains a value that can be converted to a Java double primitive type.

doubleRange

Determines whether the field being validated contains a Java double primitive type value that falls within the specified range.

email

Determines whether the field being validated contains a value that is a properly formatted e-mail address.

float

Determines whether the field being validated contains a value that can be converted to a Java float primitive type.

floatLocale

Determines whether the field being validated contains a value that can be converted to a Java float primitive type using the number formatting conventions of the current user's locale.

floatRange

Determines whether the field being validated contains a Java float primitive type value that falls within the specified range.

integer

Determines whether the field being validated contains a value that can be converted to a Java int primitive type.

integerLocale

Determines whether the field being validated contains a value that can be converted to a Java int primitive type using the number formatting conventions of the current user's locale.

intRange

Determines whether the field being validated contains a Java int primitive type value that falls within the specified range.

long

Determines whether the field being validated contains a value that can be converted to a Java long primitive type.

longLocale

Determines whether the field being validated contains a value that can be converted to a Java long primitive type using the number formatting conventions of the current user's locale.

longRange

Determines whether the field being validated contains a Java long primitive type value that falls within the specified range.

mask

Determines whether the field being validated contains a value that is properly formatted according to a specified regular expression.

maxlength

Determines whether the field being validated contains a value whose character length is less than the specified maximum length.

minlength

Determines whether the field being validated contains a value whose character length is more than the specified minimum length.

required

Determines whether the field being validated contains a value other than white space (i.e., space, tab, and newline characters).

requiredif

Deprecated. Originally used for creating conditional validations. Use the validwhen validation instead.

short

Determines whether the field being validated contains a value that can be converted to a Java short primitive type.

shortLocale

Determines whether the field being validated contains a value that can be converted to a Java short primitive type using the number formatting conventions of the current user's locale.

url

Determines whether the field being validated contains a value that is a properly formatted URL.

validwhen

Determines whether the field being validated is required based on a specified test condition.

The byte Validation

The byte validation is used to determine whether the field being validated contains a value that can be converted to a Java byte primitive type. If the conversion succeeds, the validation passes. The following snippet illustrates how to configure a byte validation in a Validator configuration file:

<field property="testByte" depends="required, byte">   <arg position="0" key="label.sampleForm.testByte"/> </field>

Configuring the byte validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the byte validation's error message.

The byte validation is set up in the preconfigured validator-rules.xml file to use the errors.byte entry in the resource bundle file for its error message. The default errors.byte entry is shown next:

errors.byte={0} must be a byte.

The byteLocale Validation

The byteLocale validation is used to determine whether the field being validated contains a value that can be converted to a Java byte primitive type using the number formatting conventions of the current user's locale. If the conversion succeeds, the validation passes. This validation works identically to the byte validation except that it uses the user's locale to constrain the values that will be valid. The following snippet illustrates how to configure a byteLocale validation in a Validator configuration file:

<field property="testByte" depends="required, byteLocale">   <arg position="0" key="label.sampleForm.testByte"/> </field>

Configuring the byteLocale validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the byteLocale validation's error message.

The byteLocale validation is set up in the preconfigured validator-rules.xml file to use the errors.byte entry in the resource bundle file for its error message. The default errors. byte entry is shown next:

errors.byte={0} must be a byte.

The creditCard Validation

The creditCard validation is used to determine whether the field being validated contains a valid credit card number from one of the four major credit card companies (American Express, Discover, MasterCard, or Visa). If the credit card number passes a checksum routine, the validation passes. The following snippet illustrates how to configure a creditCard validation in a Validator configuration file:

<field property="cardNumber" depends="required, creditCard">   <arg position="0" key="label.sampleForm.cardNumber"/> </field>

Configuring the creditCard validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the creditCard validation's error message.

The creditCard validation is set up in the preconfigured validator-rules.xml file to use the errors.creditcard entry in the resource bundle file for its error message. The default errors.creditcard entry is shown next:

errors.creditcard={0} is an invalid credit card number.

The date Validation

The date validation is used to determine whether the field being validated contains a value that can be converted to a java.util.Date type using the java.text.SimpleDateFormat class. If the conversion succeeds, the validation passes. The following snippet illustrates how to configure a date validation in a Validator configuration file:

<field property="birthDate" depends="required, date">   <arg position="0" key="label.sampleForm.birthDate"/>   <var>     <var-name>datePattern</var-name>     <var-value>MM/dd/yyyy</var-value>   </var> </field>

or

<field property="birthDate" depends="required, date">   <arg position="0" key="label.sampleForm.birthDate"/>   <var>     <var-name>datePatternStrict</var-name>     <var-value>MM/dd/yyyy</var-value>   </var> </field>

To configure the date validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the date validation's error message. Additionally, you must use the var tag to define a datePattern or datePatternStrict variable. The datePattern variable is used by the date validation to specify the pattern that dates must have in order to pass the validation. The datePatternStrict variable works the same way as the datePattern variable except that it requires that dates adhere strictly to the pattern by matching the pattern's length. For example, a date value of "6/12/2006" would not match the pattern of "MM/dd/yyyy" with the datePatternStrict variable because it wasn't "06/12/2006" (notice the leading zero on the day). The abbreviated date would, however, match with the datePattern variable. The datePattern and datePatternStrict variables accept any pattern accepted by the java.text.SimpleDateFormat class.

The date validation is set up in the preconfigured validator-rules.xml file to use the errors.date entry in the resource bundle file for its error message. The default errors.date entry is shown next:

errors.date={0} is not a date.

The double Validation

The double validation is used to determine whether the field being validated contains a value that can be converted to a Java double primitive type. If the conversion succeeds, the validation passes. The following snippet illustrates how to configure a double validation in a Validator configuration file:

<field property="orderTotal" depends="required, double">   <arg position="0" key="label.sampleForm.orderTotal"/> </field> 

Configuring the double validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the double validation's error message.

The double validation is set up in the preconfigured validator-rules.xml file to use the errors.double entry in the resource bundle file for its error message. The default errors. double entry is shown next:

errors.double={0} must be a double.

The doubleRange Validation

The doubleRange validation is used to determine whether the field being validated contains a Java double primitive type value that falls within the specified range. If the value is within the specified range, the validation passes. The following snippet illustrates how to configure a doubleRange validation in a Validator configuration file:

<field property="orderTotal" depends="required, doubleRange">   <arg position="0" key="label.sampleForm.orderTotal"/>   <arg position="1" key="${var:min}" resource="false"/>   <arg position="2" key="${var:max}" resource="false"/>   <var>     <var-name>min</var-name>     <var-value>100</var-value>   </var>   <var>     <var-name>max</var-name>     <var-value>1000</var-value>   </var> </field>

To configure the doubleRange validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use arg tags to specify the keys for values in the application resource bundle file or literal values that will be used to populate the doubleRange validation's error message. Additionally, you must use var tags to define min and max variables. The min and max variables are used by the doubleRange validation to specify the minimum and maximum values for the range, respectively. Notice that the arg tags' keys are set to $var:min and $var:max. The min and max values specified with the var tags will be used to populate the error message, respectively.

The doubleRange validation is set up in the preconfigured validator-rules.xml file to use the errors.range entry in the resource bundle file for its error message. The default errors.range entry is shown next:

errors.range={0} is not in the range {1} through {2}.

The email Validation

The email validation is used to determine whether the field being validated contains a value that is a properly formatted e-mail address. If the format is correct, the validation passes. The following snippet illustrates how to configure an email validation in a Validator configuration file:

<field property="emailAddress" depends="required, email">   <arg position="0" key="label.sampleForm.emailAddress"/> </field> 

Configuring the email validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the email validation's error message.

The email validation is set up in the preconfigured validator-rules.xml file to use the errors.email entry in the resource bundle file for its error message. The default errors.email entry is shown next:

errors.email={0} is an invalid e-mail address.

The float Validation

The float validation is used to determine whether the field being validated contains a value that can be converted to a Java float primitive type. If the conversion succeeds, the validation passes. The following snippet illustrates how to configure a float validation in a Validator configuration file:

<field property="orderTotal" depends="required, float">   <arg position="0" key="label.sampleForm.orderTotal"/> </field>

Configuring the float validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the float validation's error message.

The float validation is set up in the preconfigured validator-rules.xml file to use the errors.float entry in the resource bundle file for its error message. The default errors.float entry is shown next:

errors.float={0} must be a float.

The floatLocale Validation

The floatLocale validation is used to determine whether the field being validated contains a value that can be converted to a Java float primitive type using the number formatting conventions of the current user's locale. If the conversion succeeds, the validation passes. This validation works identically to the float validation except that it uses the user's locale to constrain the values that will be valid. The following snippet illustrates how to configure a floatLocale validation in a Validator configuration file:

<field property="orderTotal" depends="required, floatLocale">   <arg position="0" key="label.sampleForm.orderTotal"/> </field>

Configuring the floatLocale validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the floatLocale validation's error message.

The floatLocale validation is set up in the preconfigured validator-rules.xml file to use the errors.float entry in the resource bundle file for its error message. The default errors. float entry is shown next:

errors.float={0} must be a float. 

The floatRange Validation

The floatRange validation is used to determine whether the field being validated contains a Java float primitive type value that falls within the specified range. If the value is within the range, the validation passes. The following snippet illustrates how to configure a floatRange validation in a Validator configuration file:

<field property="orderTotal" depends="required, floatRange">   <arg position="0" key="label.sampleForm.orderTotal"/>   <arg position="1" key="${var:min}" resource="false"/>   <arg position="2" key="${var:max}" resource="false"/>   <var>     <var-name>min</var-name>     <var-value>100</var-value>   </var>   <var>     <var-name>max</var-name>     <var-value>1000</var-value>   </var> </field>

To configure the floatRange validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use arg tags to specify the keys for values in the application resource bundle file or literal values that will be used to populate the floatRange validation's error message. Additionally, you must use var tags to define min and max variables. The min and max variables are used by the floatRange validation to specify the minimum and maximum values for the range, respectively. Notice that the arg tags' keys are set to $var:min and $var:max. The min and max values specified with the var tags will be used to populate the error message, respectively.

The floatRange validation is set up in the preconfigured validator-rules.xml file to use the errors.range entry in the resource bundle file for its error message. The default errors. range entry is shown next:

errors.range={0} is not in the range {1} through {2}.

The integer Validation

The integer validation is used to determine whether the field being validated contains a value that can be converted to a Java int primitive type. If the conversion succeeds, the validation passes. The following snippet illustrates how to configure an integer validation in a Validator configuration file:

<field property="productCount" depends="required, integer">   <arg position="0" key="label.sampleForm.productCount"/> </field>

Configuring the integer validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the integer validation's error message.

The integer validation is set up in the preconfigured validator-rules.xml file to use the errors.integer entry in the resource bundle file for its error message. The default errors. integer entry is shown next:

errors.integer={0} must be an integer. 

The integerLocale Validation

The integerLocale validation is used to determine whether the field being validated contains a value that can be converted to a Java int primitive type using the number formatting conventions of the current user's locale. If the conversion succeeds, the validation passes. This validation works identically to the integer validation except that it uses the user's locale to constrain the values that will be valid. The following snippet illustrates how to configure an integerLocale validation in a Validator configuration file:

<field property="productCount" depends="required, integerLocale">   <arg position="0" key="label.sampleForm.productCount"/> </field>

Configuring the integerLocale validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the integerLocale validation's error message.

The integerLocale validation is set up in the preconfigured validator-rules.xml file to use the errors.integer entry in the resource bundle file for its error message. The default errors.integer entry is shown next:

errors.integer={0} must be an integer.

The intRange Validation

The intRange validation is used to determine whether the field being validated contains a Java int primitive type value that falls within the specified range. If the value is within the range, the validation passes. The following snippet illustrates how to configure an intRange validation in a Validator configuration file:

<field property="orderTotal" depends="required, intRange">   <arg position="0" key="label.sampleForm.orderTotal"/>   <arg position="1" key="${var:min}" resource="false"/>   <arg position="2" key="${var:max}" resource="false"/>   <var>     <var-name>min</var-name>     <var-value>100</var-value>   </var>   <var>     <var-name>max</var-name>     <var-value>1000</var-value>   </var> </field>

To configure the intRange validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use arg tags to specify the keys for values in the application resource bundle file or literal values that will be used to populate the intRange validation's error message. Additionally, you must use var tags to define min and max variables. The min and max variables are used by the intRange validation to specify the minimum and maximum values for the range, respectively. Notice that the arg tags' keys are set to $var:min and $var:max. The min and max values specified with the var tags will be used to populate the error message, respectively.

The intRange validation is set up in the preconfigured validator-rules.xml file to use the errors.range entry in the resource bundle file for its error message. The default errors. range entry is shown next:

errors.range={0} is not in the range {1} through {2}.

The long Validation

The long validation is used to determine whether the field being validated contains a value that can be converted to a Java long primitive type. If the conversion succeeds, the validation passes. The following snippet illustrates how to configure a long validation in a Validator configuration file:

<field property="productCount" depends="required, long">   <arg position="0" key="label.sampleForm.productCount"/> </field>

Configuring the long validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the long validation's error message.

The long validation is set up in the preconfigured validator-rules.xml file to use the errors.long entry in the resource bundle file for its error message. The default errors.long entry is shown next:

errors.long={0} must be a long.

The longLocale Validation

The longLocale validation is used to determine whether the field being validated contains a value that can be converted to a Java long primitive type using the number formatting conventions of the current user's locale. If the conversion succeeds, the validation passes. This validation works identically to the long validation except that it uses the user's locale to constrain the values that will be valid. The following snippet illustrates how to configure a longLocale validation in a Validator configuration file:

<field property="productCount" depends="required, longLocale">   <arg position="0" key="label.sampleForm.productCount"/> </field>

Configuring the longLocale validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the longLocale validation's error message.

The longLocale validation is set up in the preconfigured validator-rules.xml file to use the errors.long entry in the resource bundle file for its error message. The default errors. long entry is shown next:

errors.long={0} must be a long.

The longRange Validation

The longRange validation is used to determine whether the field being validated contains a Java long primitive type value that falls within the specified range. If the value is within the range, the validation passes. The following snippet illustrates how to configure a longRange validation in a Validator configuration file:

<field property="orderTotal" depends="required, longRange">   <arg position="0" key="label.sampleForm.orderTotal"/>   <arg position="1" key="${var:min}" resource="false"/>   <arg position="2" key="${var:max}" resource="false"/>   <var>     <var-name>min</var-name>     <var-value>100</var-value>   </var>   <var>     <var-name>max</var-name>     <var-value>1000</var-value>   </var> </field>

To configure the longRange validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use arg tags to specify the keys for values in the application resource bundle file or literal values that will be used to populate the longRange validation's error message. Additionally, you must use var tags to define min and max variables. The min and max variables are used by the longRange validation to specify the minimum and maximum values for the range, respectively. Notice that the arg tags' keys are set to $var:min and $var:max. The min and max values specified with the var tags will be used to populate the error message, respectively.

The longRange validation is set up in the preconfigured validator-rules.xml file to use the errors.range entry in the resource bundle file for its error message. The default errors. range entry is shown next:

errors.range={0} is not in the range {1} through {2}.

The mask Validation

The mask validation is used to determine whether the field being validated contains a value that is properly formatted according to a specified regular expression. If the value's format matches the regular expression, the validation passes. The following snippet illustrates how to configure a mask validation in a Validator configuration file:

<field property="socialSecurityNum" depends="required, mask">   <arg position="0" key="label.sampleForm.socialSecurityNum"/>   <var>     <var-name>mask</var-name>     <var-value>^\d{3}-\d{2}-\d{4}$</var-value>   </var> </field>

To configure the mask validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the mask validation's error message. Additionally, you must use the var tag to define a mask variable. The mask variable is used by the mask validation to specify a regular expression to which values must conform in order to be deemed valid.

Note 

Regular expressions are a powerful tool for text analysis and manipulation; however, they constitute a large, and at times complex, topic. Therefore, a discussion of regular expressions is outside the scope of this book.

The mask validation is set up in the preconfigured validator-rules.xml file to use the errors.invalid entry in the resource bundle file for its error message. The default errors. invalid entry is shown next:

errors.invalid={0} is invalid.

The maxlength Validation

The maxlength validation is used to determine whether the field being validated contains a value whose character length is less than the specified maximum length. If the value contains fewer characters than the specified maximum, the validation passes. The following snippet illustrates how to configure a maxlength validation in a Validator configuration file:

<field property="password" depends="required, maxlength">   <arg position="0" key="label.sampleForm.password"/>   <arg position="1" key="${var:maxlength}" resource="false"/>   <var>     <var-name>maxlength</var-name>     <var-value>8</var-value>   </var> </field>

To configure the maxlength validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use arg tags to specify the keys for values in the application resource bundle file or literal values that will be used to populate the maxlength validation's error message. Additionally, you must use the var tag to define a maxlength variable. The maxlength variable is used by the maxlength validation to specify the maximum character length that values can have. Notice that the arg tag's key is set to $var:maxlength. The maxlength value specified with the var tag will be used to populate the error message.

The maxlength validation is set up in the preconfigured validator-rules.xml file to use the errors.maxlength entry in the resource bundle file for its error message. The default errors.maxlength entry is shown next:

errors.maxlength={0} can not be greater than {1} characters.

The minlength Validation

The minlength validation is used to determine whether the field being validated contains a value whose character length is more than the specified minimum length. If the value contains more characters than the specified minimum, the validation passes. The following snippet illustrates how to configure a minlength validation in a Validator configuration file:

<field property="password" depends="required, minlength">   <arg position="0" key="label.sampleForm.password"/>   <arg position="1" key="${var:minlength}" resource="false"/>   <var>     <var-name>minlength</var-name>     <var-value>4</var-value>   </var> </field>

To configure the minlength validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use arg tags to specify the keys for values in the application resource bundle file or literal values that will be used to populate the minlength validation's error message. Additionally, you must use the var tag to define a minlength variable. The minlength variable is used by the minlength validation to specify the minimum character length that values can have. Notice that the arg tag's key is set to $var:minlength. The minlength value specified with the var tag will be used to populate the error message.

The minlength validation is set up in the preconfigured validator-rules.xml file to use the errors.minlength entry in the resource bundle file for its error message. The default errors.minlength entry is shown next:

errors.minlength={0} can not be less than {1} characters.

The required Validation

The required validation is used to determine whether the field being validated contains a value other than white space (i.e., space, tab, and newline characters). If a non–white space value is present, the validation passes. The following snippet illustrates how to configure a required validation in a Validator configuration file:

<field property="name" depends="required">   <arg position="0" key="label.sampleForm.name"/> </field>

Configuring the required validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the required validation's error message.

The required validation is set up in the preconfigured validator-rules.xml file to use the errors.required entry in the resource bundle file for its error message. The default errors. required entry is shown next:

errors.required={0} is required.

The short Validation

The short validation is used to determine whether the field being validated contains a value that can be converted to a Java short primitive type. If the conversion succeeds, the validation passes. The following snippet illustrates how to configure a short validation in a Validator configuration file:

<field property="productCount" depends="required, short">   <arg position="0" key="label.sampleForm.productCount"/> </field>

Configuring the short validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the short validation's error message.

The short validation is set up in the preconfigured validator-rules.xml file to use the errors.short entry in the resource bundle file for its error message. The default errors.short entry is shown next:

errors.short={0} must be a short.

The shortLocale Validation

The shortLocale validation is used to determine whether the field being validated contains a value that can be converted to a Java short primitive type using the number formatting conventions of the current user's locale. If the conversion succeeds, the validation passes. This validation works identically to the short validation except that it uses the user's locale to constrain the values that will be valid. The following snippet illustrates how to configure a shortLocale validation in a Validator configuration file:

<field property="productCount" depends="required, shortLocale">   <arg position="0" key="label.sampleForm.productCount"/> </field>

Configuring the shortLocale validation is straightforward: you specify it in the list of validations for the given field with the depends attribute of the field tag. You must also use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the shortLocale validation's error message.

The shortLocale validation is set up in the preconfigured validator-rules.xml file to use the errors.short entry in the resource bundle file for its error message. The default errors. short entry is shown next:

errors.short={0} must be a short.

The url Validation

The url validation is used to determine whether the field being validated contains a value that is a properly formatted URL. If the format is correct, the validation passes. The following snippet illustrates how to configure a url validation in a Validator configuration file:

<field property="websiteUrl" depends="required, url">   <arg position="0" key="label.sampleForm.websiteUrl"/> </field>

To configure the url validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the url validation's error message. Additionally, you can use var tags to define four optional variables: allowallschemes, allow2slashes, nofragments, and schemes.

The allowallschemes and schemes variables are used to specify which URL schemes are acceptable when the url validation is determining if a URL is valid or not. The schemes variable allows you to specify a list of schemes the URL must have in order to pass the validation, as shown here:

<field property="websiteUrl" depends="required, url">    <arg position="0" key="label.sampleForm.websiteUrl"/>   <var>     <var-name>schemes</var-name>     <var-value>http,https</var-value>   </var> </field>

In this example, only URLs having the "http" or "https" schemes will be valid (e.g., http://domain.com or https://domain.com). A URL with an "ftp" scheme (e.g., ftp://domain.com) would be invalid. The allowallschemes variable, shown next, accepts true or false to specify whether the url validation will accept any scheme. This variable defaults to false.

<field property="websiteUrl" depends="required, url">   <arg position="0" key="label.sampleForm.websiteUrl"/>   <var>     <var-name>allowallschemes</var-name>     <var-value>true</var-value>   </var> </field>

Note that the allowallschemes variable overrides the schemes variable if both are specified.

The allow2slashes variable accepts true or false to specify whether double slash (/) characters are allowed in the path of URLs (e.g., http://domain.com/dir1//page.html). This variable defaults to false. The nofragments variable accepts true or false to specify whether URL fragments (i.e., anchors) are allowed to be a part of acceptable URLs. This variable defaults to false meaning that fragments are allowed (e.g., http://domain.com/page.html#fragment).

The url validation is set up in the preconfigured validator-rules.xml file to use the errors.url entry in the resource bundle file for its error message. The default errors.url entry is shown next:

errors.url={0} is an invalid URL.

The validwhen Validation

The validwhen validation is used to determine whether the field being validated is required based on a specified test condition. If the test condition succeeds, the validation passes.

The following snippet illustrates how to configure a validwhen validation in a Validator configuration file:

<field property="emailConfirm" depends="validwhen">   <arg position="0" key="label.sampleForm.emailConfirm"/>   <var>     <var-name>test</var-name>     <var-value>((email == null) or (*this* != null))</var-value>   </var> </field>

To configure the validwhen validation, you specify it in the list of validations for the given field with the depends attribute of the field tag. You must use an arg tag to specify the key for a value in the application resource bundle file or a literal value that will be used to populate the validwhen validation's error message. Additionally, you must use the var tag to define a test variable. The test variable is used by the validwhen validation to specify a test condition that must pass in order for the validation to succeed.

The test condition specified with the test variable is designed to allow for dependent validations to be defined. Dependent validations are validations where one field's validity is based on the value of another field. For example, an email confirmation field may

be required only if a related email field has a value. There is no way to define this interdependent requirement with the standard required validation. With the validwhen validation, however, you can create a validation dependency from one field to another, as was shown in the previous configuration example.

The test variable's test condition is a Boolean expression that must evaluate to true in order for the validation to succeed. Following is the list of rules governing the syntax for creating test conditions:

  • Form fields are referenced by their logical name (e.g., name, email, etc.).

  • The field for which the validation is being performed is referenced as *this*.

  • null is used to indicate null or an empty string.

  • Literal string values must be single- or double-quoted.

  • Literal integer values can be specified using decimal, hex, or octal formats.

  • All comparisons must be enclosed in parentheses.

  • A maximum of two comparisons can be made in one condition using and or or.

  • A numeric comparison is performed for conditions that have two numerical values; otherwise, a string comparison is performed.

The validwhen validation is set up in the preconfigured validator-rules.xml file to use the errors.required entry in the resource bundle file for its error message. The default errors.required entry is shown next:

errors.required={0} is required.

Enabling Client-Side Validations

In addition to providing a framework for simplifying server-side form data validations, Validator provides an easy-to-use mechanism for performing client-side validations. Each validation routine defined in the validator-rules.xml file optionally specifies JavaScript code that can be run in the browser (client side) to perform the same validations that take place on the server side. When run on the client side, the validations will not allow the form to be submitted until they have all passed. Validations that fail will trigger error dialog windows that specify the fields and the type of validation that failed. Figure 6-1 shows a sample error dialog triggered from a failed validation.

image from book
Figure 6-1: Validator's client-side JavaScript error dialog

To enable client-side validation, you have to place the HTML Tag Library's javascript tag in each JSP for which you want client-side validation performed, as shown here:

<html:javascript formName="logonForm"/>

The javascript tag outputs the JavaScript code necessary to run all of a form's configured validations on the client-side. Note that the javascript tag requires that you use the formName attribute to specify the name of a <form> definition from the validation.xml file, as shown here, for which you want validations performed:

 <form name="logonForm">   <field property="username" depends="required">     <arg position="0" key="prompt.username"/>   </field>   <field property="password" depends="required">     <arg position="0" key="prompt.password"/>   </field> </form>

All the validations that you have specified for the <form> definition to run on the server side will be run on the client side.

After adding the javascript tag to your page, you must update the HTML Tag Library's form tag to have an onsubmit attribute. The onsubmit attribute is used to specify JavaScript code that is executed when the form is submitted.

In addition to outputting all of the JavaScript code for the validation routines, the javascript tag generates a master JavaScript validation method that is used to invoke all of the configured validations for the form. This master method must be called from the onsubmit attribute of the form tag. Following is an example of how to specify the onsubmit attribute for Validator's client-side validations:

<html:form action="/Logon" onsubmit="return validateLogonForm(this);">

The master validation method generated by the javascript tag is named based on concatenating "validate" with the name of the form name specified with the formName attribute of the javascript tag. For example, a form named "searchForm" will have a generated method named "validateSearchForm".

Note 

The method attribute of the javascript tag can be used to specify an alternate method name for the master method that Validator generates. This is useful in scenarios where the auto-generated method name conflicts with other JavaScript method names in your application.

Understanding the Client-Side Validation Process

Validator's client-side validations are performed in a specific order and, as previously mentioned, trigger error dialog windows upon failure. It's important to understand the sequence in which validations are performed in order to understand when error dialogs are triggered. Validator's client-side JavaScript processes validations based on the order they are specified in the validation.xml file for a form. Validator proceeds field-by-field processing the validations, but there is one important detail about how the validations are processed. Once a validation is run for a field, for example, the required validation, all fields that are to be validated using that validation are run at that time. That is, instead of running a validation each time it is specified in the order it is specified, it is run once for all fields that specify it and then the next validation is processed.

Validator stops processing validations and triggers an error dialog window if any fields being validated by a particular validation fail. This behavior can sometimes be frustrating for users of an application who submit a form that has several validations on it. If multiple validations fail, the user will be prompted only for the first validation that fails. The user can then fix the field(s) with errors and submit the form again. If the validation that failed the first time passes and another validation fails, another error dialog will be displayed. This back-and-forth process of alerting the user of which fields failed validation and then resubmitting the form again for another run of the validations can be cumbersome for the user. The basic problem is that Validator stops processing validations and displays an error dialog for only the first validation that fails. This is the default behavior. However, Validator supports an option for processing all validations, whether they fail or not, and then displaying error dialogs for each validation that failed after all validations have been processed. To enable this option, you have to update the Validator <plug-in> definition

in the Struts configuration file, as shown next:

<!-- Validator Configuration --> <plug-in className="org.apache.struts.validator.ValidatorPlugIn">   <set-property property="pathnames"                    value="/org/apache/struts/validator/validator-rules.xml,                           /WEB-INF/validation.xml"/>   <set-property property="stopOnFirstError" value="false"/> </plug-in>

The stopOnFirstError property has to be set to false in order to have Validator process all validations and then display error dialogs for each failed validation. Each validation that fails will have its own error dialog listing each of the fields that failed that particular validation.

Creating a Common Client-Side Validations JSP

The HTML Tag Library's javascript tag outputs the JavaScript code for all validation routines independent of whether they are used or not. For example, even if a form on a page has only two fields and makes use of only the required validation for those fields, the javascript tag outputs the JavaScript code for the required validation and all other validations configured in the validator-rules.xml file. This can add a large amount of unnecessary page download overhead to each page making use of client-side validations.

To get around all of the validations being inserted into each page, you can create a common client-side validations JSP that will house the JavaScript for all validations. Each page that makes use of client-side validation will link to the common page, instead of embedding the validations inline. This approach allows the browser to cache the common validations page, thus eliminating the unnecessary overheard of downloading the validation code for every request of each page. To make use of a common validations JSP, you must first create the common JSP, as shown next:

<%@ page contentType="application/x-javascript" language="java" %> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>     <html:javascript dynamicJavascript="false" staticJavascript="true"/> 

This page is typically named staticJavascript.jsp; however, the name is entirely up to you. Notice that this page uses the javascript tag with the dynamicJavascript and staticJavascript attributes set to false and true, respectively. This instructs the javascript tag to output only the JavaScript code for the validation routines and not the code that invokes the routines for the fields of a form. The JavaScript code that invokes the routines is dynamic and must be housed in each of the individual JSPs utilizing client-side validation. Following is the snippet that must be placed in each of the individual JSPs utilizing client-side validation.

<html:javascript formName="LogonForm"         dynamicJavascript="true"          staticJavascript="false"/> <script language="JavaScript" src="/books/1/249/1/html/2/staticJavascript.jsp"></script>

Notice that the javascript tag's dynamicJavascript and staticJavascript attributes are set to true and false respectively in the individual pages; this is the opposite of how they are set in the staticJavascript.jsp page. In addition to using the javascript tag to emit the dynamic JavaScript code, you must use a script tag to link to the common validations JSP.



Struts. The Complete Reference
Struts: The Complete Reference, 2nd Edition
ISBN: 0072263865
EAN: 2147483647
Year: 2004
Pages: 165
Authors: James Holmes

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net