org.apache.commons.validator |
Package Documentation for org.apache.commons.validator
The Validator package provides validation for JavaBeans based on an xml file.
Introduction
A common issue when receiving data either electronically or from
user input is verifying the integrity of the data. This work is
repetitive and becomes even more complicated when different sets
of validation rules need to be applied to the same set of data based
on locale for example. Error messages may also vary by locale.
This package attempts to address some of these issues and
speed development and maintenance of validation rules.
In order to use the Validator, the following basic steps are required:
- Create a new instance of the
org.apache.commons.validator.Validator class. Currently
Validator instances may be safely reused if the current ValidatorResources
are the same, as long as
you have completed any previous validation, and you do not try to utilize
a particular Validator instance from more than one thread at a time.
- Add any resources
needed to perform the validations. Such as the JavaBean to validate.
- Call the validate method on
org.apache.commons.validator.Validator .
Overview
The Commons Validator is a basic validation framework that
lets you define validation rules for a JavaBean in an xml file.
Validators, the validation definition, can also be defined in
the xml file. An example of a validator would be defining
what method and class will be called to perform the validation
for a required field. Validation rules can be grouped together
based on locale and a JavaBean/Form that the rules are associated
with. The framework has basic support for user defined constants
which can be used in some field attributes.
Validation rules can be defined in an xml file which keeps
them abstracted from JavaBean you are validating. The
property reference to a field supports nested properties
using the Jakarta Commons BeanUtils
(http://jakarta.apache.org/commons/beanutils.html) package.
Error messages and the arguments for error messages can be
associated with a fields validation.
Resources
After a Validator instance is created, instances of
classes can be added to it to be passed into
validation methods by calling the setParameter()
method. Below is a list of reserved parameters (class names).
Class Name |
Validator Contstant |
Description |
java.lang.Object |
Validator.BEAN_PARAM |
JavaBean that is being validated |
java.util.Locale |
Validator.LOCALE_PARAM |
Locale to use when retrieving a FormSet.
The default locale will be used if one
isn't specified.
|
org.apache.commons.validator.ValidatorAction |
Validator.VALIDATOR_ACTION_PARAM |
This is automatically added to a Validator's
resources as a validation is being processed.
If this class name is used when defining
a method signature for a pluggable validator,
the current ValidatorAction will be passed into
the validation method.
|
org.apache.commons.validator.Field |
Validator.FIELD_PARAM |
This is automatically added to a Validator's
resources as a validation is being processed.
If this class name is used when defining
a method signature for a pluggable validator,
the current Field will be passed into
the validation method.
|
Usage Example
This is a basic example setting up a required validator for
a name bean. This example is a working unit test (reference
org.apache.commons.validator.RequiredNameTest and
validator-name-required.xml located under validator/src/test).
Create an xml file with your validator and validation rules.
Setup your required validator in your xml file.
XML Example
Validator Example
Pluggable Validator Example
XML Example
Definition of a 'required' pluggable validator.
<form-validation>
<global>
<validator name="required"
classname="org.apache.commons.validator.TestValidator"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.Field"/>
</global>
<formset>
</formset>
</form-validation>
Add validation rules to require a first name and a last name.
<form-validation>
<global>
<validator name="required"
classname="org.apache.commons.validator.TestValidator"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.Field"/>
</global>
<formset>
<form name="nameForm">
<field property="firstName"
depends="required">
<arg0 key="nameForm.firstname.displayname"/>
</field>
<field property="lastName"
depends="required">
<arg0 key="nameForm.lastname.displayname"/>
</field>
</form>
</formset>
</form-validation>
Validator Example
Excerpts from org.apache.commons.validator.RequiredNameTest
InputStream in = this.getClass().getResourceAsStream("validator-name-required.xml");
// Create an instance of ValidatorResources to
// initialize from an xml file.
ValidatorResources resources = new ValidatorResources(in);
// Create bean to run test on.
Name name = new Name();
// Construct validator based on the loaded resources
// and the form key
Validator validator = new Validator(resources, "nameForm");
// add the name bean to the validator as a resource
// for the validations to be performed on.
validator.setParameter(Validator.BEAN_PARAM, name);
// Get results of the validation.
Map results = null;
// throws ValidatorException,
// but aren't catching for example
results = validator.validate();
if (results.get("firstName") == null) {
// no error
} else {
// number of errors for first name
int errors = ((Integer)results.get("firstName")).intValue();
}
Pluggable Validator Example
Validation method defined in the 'required' pluggable validator
(excerpt from org.apache.commons.validator.TestValidator).
public static boolean validateRequired(Object bean, Field field) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
return GenericValidator.isBlankOrNull(value);
}
|
org.apache.commons.validator.routines |
Package Documentation for org.apache.commons.validator.routines Package
This package contains independant validation routines.
Table of Contents
1. Overview
Commons Validator serves two purposes:
- To provide standard, independant validation routines/functions.
- To provide a mini framework for Validation.
This package has been created, since version 1.3.0, in an attempt to clearly
separate these two concerns and is the location for the standard, independant
validation routines/functions in Commons Validator.
The contents of this package have no dependencies on the framework aspect of
Commons Validator and can be used on their own.
2. Date and Time Validators
2.1 Overview
The date and time validators either validate according to a specified format
or use a standard format for a specified Locale .
2.2 Validating a Date Value
You can either use one of the isValid() methods to just determine
if a date is valid, or use one of the validate() methods to
validate a date and convert it to a java.util.Date ...
// Get the Date validator
DateValidator validator = DateValidator.getInstance();
// Validate/Convert the date
Date fooDate = validator.validate(fooString, "dd/MM/yyyy");
if (fooDate == null) {
// error...not a valid date
return;
}
The following methods are provided to validate a date/time (return a boolean result):
isValid(value)
isValid(value, pattern)
isValid(value, Locale)
isValid(value, pattern, Locale)
The following methods are provided to validate a date/time and convert it to either a
java.util.Date or java.util.Calendar :
validate(value)
validate(value, pattern)
validate(value, Locale)
validate(value, pattern, Locale)
2.3 Formatting
Formatting and validating are two sides of the same coin. Typically
input values which are converted from Strings according to a
specified format also have to be rendered for output in
the same format. These validators provide the mechanism for formatting from
date/time objects to Strings. The following methods are provided to format
date/time values as Strings:
format(date/calendar)
format(date/calendar, pattern)
format(date/calendar, Locale)
format(date/calendar, pattern, Locale)
2.4 Time Zones
If the date being parsed relates to a different time zone than the
system default, you can specify the TimeZone to use when
validating/converting:
// Get the GMT time zone
TimeZone GMT = TimeZone.getInstance("GMT");
// Validate/Convert the date using GMT
Date fooDate = validator.validate(fooString, "dd/MM/yyyy", GMT);
The followng Time Zone flavours of the Validation/Conversion methods
are provided:
validate(value, TimeZone)
validate(value, pattern, TimeZone)
validate(value, Locale, TimeZone)
validate(value, pattern, Locale, TimeZone)
2.5 Comparing Dates and Times
As well as validating that a value is a valid date or time, these validators
also provide date comparison functions. The DateValidator
and CalendarValidator provide functions for comparing years,
quarters, months, weeks and dates and the TimeValidator provides
functions for comparing hours, minutes, seconds and milliseconds.
For example, to check that a date is in the current month, you could use
the compareMonths() method, which compares the year and month
components of a date:
// Check if the date is in the current month
int compare = validator.compareMonths(fooDate, new Date(), null);
if (compare == 0) {
// do current month processing
return;
}
// Check if the date is in the previous quarter
compare = validator.compareQuarters(fooDate, new Date(), null);
if (compare < 0) {
// do previous quarter processing
return;
}
// Check if the date is in the next year
compare = validator.compareYears(fooDate, new Date(), null);
if (compare > 0) {
// do next year processing
return;
}
3 Numeric Validators
3.1 Overview
The numeric validators either validate according to a specified format
or use a standard format for a specified Locale or use
a custom format for a specified Locale .
3.2 Validating a Numeric Value
You can either use one of the isValid() methods to just determine
if a number is valid, or use one of the validate() methods to
validate a number and convert it to an appropriate type.
The following example validates an integer against a custom pattern
for the German locale. Please note the format is specified using
the standard symbols for java.text.DecimalFormat so although
the decimal separator is indicated as a period (".") in the format, the
validator will check using the German decimal separator - which is a comma (",").
// Get the Integer validator
IntegerValidator validator = IntegerValidator.getInstance();
// Validate/Convert the number
Integer fooInteger = validator.validate(fooString, "#,##0.00", Locale.GERMAN);
if (fooInteger == null) {
// error...not a valid Integer
return;
}
The following methods are provided to validate a number (return a boolean result):
isValid(value)
isValid(value, pattern)
isValid(value, Locale)
isValid(value, pattern, Locale)
The following methods are provided to validate a number and convert it one of
the java.lang.Number implementations:
validate(value)
validate(value, pattern)
validate(value, Locale)
validate(value, pattern, Locale)
3.3 Formatting
Formatting and validating are two sides of the same coin. Typically
input values which are converted from Strings according to a
specified format also have to be rendered for output in
the same format. These validators provide the mechanism for formatting from
numeric objects to Strings. The following methods are provided to format
numeric values as Strings:
format(number)
format(number, pattern)
format(number, Locale)
format(number, pattern, Locale)
3.4 Comparing Numbers
As well as validating that a value is a valid number, these validators
also provide functions for validating the minimum, maximum
and range of a value.
// Check the number is between 25 and 75
if (validator.isInRange(fooInteger, 25, 75) {
// valid...in the specified range
return;
}
3.5 Currency Validation
A default Currency Validator
implementation is provided, although all the numeric validators
support currency validation. The default implementation converts
currency amounts to a java.math.BigDecimal and additionally
it provides lenient currency symbol validation. That is, currency
amounts are valid with or without the currency symbol.
BigDecimalValidator validator = CurrencyValidator.getInstance();
BigDecimal fooAmount = validator.validate("$12,500.00", Locale.US);
if (fooAmount == null) {
// error...not a valid currency amount
return;
}
// Check the amount is a minimum of $1,000
if (validator.minValue(fooAmount, 1000) {
// valid...in the specified range
return;
}
If, for example, you want to use the Integer
Validator to validate a currency, then you can simply create a
new instance with the appropriate format style. Note that
the other validators do not support the lenient currency symbol
validation.
IntegerValidator validator =
new IntegerValidator(true, IntegerValidator.CURRENCY_FORMAT);
String pattern = "#,###" + '\u00A4' + '\u00A4'; // Use international symbol
Integer fooAmount = validator.validate("10.100EUR", pattern, Locale.GERMAN);
if (fooAmount == null) {
// error...not a valid currency amount
return;
}
3.6 Percent Validation
A default Percent Validator
implementation is provided, although the Float,
Double and BigDecimal validators also support
percent validation. The default implementation converts
percent amounts to a java.math.BigDecimal and additionally
it provides lenient percent symbol validation. That is, percent
amounts are valid with or without the percent symbol.
BigDecimalValidator validator = PercentValidator.getInstance();
BigDecimal fooPercent = validator.validate("20%", Locale.US);
if (fooPercent == null) {
// error...not a valid percent
return;
}
// Check the percent is between 10% and 90%
if (validator.isInRange(fooPercent, 0.1, 0.9) {
// valid...in the specified range
return;
}
If, for example, you want to use the Float
Validator to validate a percent, then you can simply create a
new instance with the appropriate format style. Note that
the other validators do not support the lenient percent symbol
validation.
FloatValidator validator =
new FloatValidator(true, FloatValidator.PERCENT_FORMAT);
Float fooPercent = validator.validate("20%", "###%");
if (fooPercent == null) {
// error...not a valid percent
return;
}
Note: in theory the other numeric validators besides
Float, Double and BigDecimal (i.e. Byte,
Short, Integer, Long and BigInteger)
also support percent validation. However, since they don't allow fractions
they will only work with percentages greater than 100%.
|