background image

Implementing the Validator Interface

<< Creating a Custom Validator | The getMessage Method >>
<< Creating a Custom Validator | The getMessage Method >>

Implementing the Validator Interface

According to this validator, the data entered in the field must be one of the following:
A 16 digit number with no spaces
A 16 digit number with a space between every four digits
A 16 digit number with hyphens between every four digits
The rest of this section describes how this validator is implemented and how to create a custom
tag so that the page author can register the validator on a component.
Implementing the Validator Interface
A Validator implementation must contain a constructor, a set of accessor methods for any
attributes on the tag, and a validate method, which overrides the validate method of the
Validator
interface.
The FormatValidator class also defines accessor methods for setting the formatPatterns
attribute, which specifies the acceptable format patterns for input into the fields. In addition, the
class overrides the validate method of the Validator interface. This method validates the
input and also accesses the custom error messages to be displayed when the String is invalid.
The validate method performs the actual validation of the data. It takes the FacesContext
instance, the component whose data needs to be validated, and the value that needs to be
validated. A validator can validate only data of a component that implements
EditableValueHolder
.
Here is the validate method from FormatValidator:
public void validate(FacesContext context, UIComponent component, Object toValidate) {
boolean valid = false;
String value = null;
if ((context == null) || (component == null)) {
throw new NullPointerException();
}
if (!(component instanceof UIInput)) {
return;
}
if ( null == formatPatternsList || null == toValidate) {
return;
}
value = toValidate.toString();
//validate the value against the list of valid patterns.
Iterator patternIt = formatPatternsList.iterator();
while (patternIt.hasNext()) {
valid = isFormatValid(
((String)patternIt.next()), value);
Creating a Custom Validator
Chapter 12 · Developing with JavaServer Faces Technology
399