The Struts framework features a built-in database for performing data validations on incoming form data. Its simple interface means that developers can focus on writing validation code; additionally, you can plug your own custom routines into Validator. This article shows you how. It is taken from chapter six of the book The Complete Reference Struts, written by James Holmes (McGraw-Hill/Osborne, 2004; ISBN: 0072231319).
By default, Validator comes packaged with several basic validation routines that you can use to solve most validation scenarios. As mentioned, the sample applications provided by Struts come packaged with preconfigured validator-rules.xml files that define these routines. Table 6-1 lists each of the preconfigured validations by logical name and states its purpose.
Note Detailed information on configuring the validator-rules.xml file is found in Chapter 18.
Validation
Description
byte
Validates that the specified field contains a valid byte.
creditCard
Validates that the specified field contains a valid credit card number.
date
Validates that the specified field contains a valid date.
double
Validates that the specified field contains a valid double.
email
Validates that the specified field contains a valid e-mail address.
float
Validates that the specified field contains a valid float.
floatRange
Validates that the specified field contains a valid float and falls within the
specified range.
integer
Validates that the specified field contains a valid integer.
intRange
Validates that the specified field contains a valid integer and falls within the
specified range.
long
Validates that the specified field contains a valid long.
TABLE 6-1 Validator’s Preconfigured Validations
Validation
Description
mask
Validates that the specified field conforms to a given regular expression (or "mask").
maxlength
Validates that the string in the specified field’s length is less than or equal to the
specified maximum length.
minlength
Validates that the string in the specified field’s length is greater than or equal to
the specified minimum length.
range
Deprecated
Use the intRange validation instead.
required
Validates that the specified field contains characters other than white space
(i.e., space, tab, and newline characters).
requiredif
Performs the required validation on the specified field if a specified rule is met.
short
Validates that the specified field contains a valid short.