Download
FAQ History |
API
Search Feedback |
Creating a Custom Validator
If the standard validators don't perform the validation checking you need, you can easily create a custom validator to validate user input. As explained in Validation Model, there are two ways to implement validation code:
Writing a Method to Perform Validation explains how to implement a backing bean to perform validation. The rest of this section explains how to implement the
Validator
interface.If you choose to implement the
Validator
interface and you want to allow the page author to configure the validator's attributes from the page, you also must create a custom tag for registering the validator on a component.If you prefer to configure the attributes in the implementation, you can forgo creating a custom tag and instead let the page author register the validator on a component using a
validator
tag. This tag simply refers to theValidator
implementation, which handles the configuration of the validator's attributes.Usually, you will want to display an error message when data fails validation. You need to store these error messages in a
ResourceBundle
. For more information on creating aResourceBundle
, see
http://java.sun.com/docs/books/tutorial/i18n/resbundle/index.html
When validation fails, you can queue the error messages onto the
FacesContext
programmatically. Alternatively, you can have the application architect register the error messages using the application configuration resource file. Registering Messages explains how to register error messages with the application.The Duke's Bookstore application uses a general-purpose custom validator (called
bookstore6/src/validators/FormatValidator
) that validates input data against a format pattern that is specified in the custom validator tag. This validator is used with the Credit Card Number field on thebookcashier.jsp
page. Here is the custom validator tag:<bookstore:formatValidator formatPatterns="9999999999999999|9999 9999 9999 9999| 9999-9999-9999-9999"/>According to this validator, the data entered in the field must be either:
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.
Implement the Validator Interface
This
Validator
implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and avalidate
method, which overrides thevalidate
method of theValidator
interface.The
FormatValidator
class also defines accessor methods for setting the attributeformatPatterns
, which specifies the acceptable format patterns for input into the fields. In addition, the class overridesvalidate
method of theValidator
interface. This method validates the input and also accesses the custom error messages to be displayed when theString
is invalid.The
validate
method performs the actual validation of the data. It takes theFacesContext
, the component whose data needs to be validated, and the value that needs to be validated. A validator can validate only data of aUIInput
component or a component that extendsUIInput
.Here is the
validate
method fromFormatValidator
: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); if (valid) { break; } } if ( !valid ) { FacesMessage errMsg = MessageFactory.getMessage(context, FORMAT_INVALID_MESSAGE_ID, (new Object[] {formatPatterns})); throw new ValidatorException(errMsg); } }This method gets the local value of the component and converts it to a
String
. It then iterates over theformatPatternsList
list, which is the list of acceptable patterns as specified in theformatPatterns
attribute of the custom validator tag.While iterating over the list, this method checks the pattern of the local value against the patterns in the list. If the pattern of the local value does not match any pattern in the list, this method generates an error message. It then passes the message to the constructor of
ValidatorException
. Eventually the message is queued onto theFacesContext
so that the message is displayed on the page during the render response phase.The error messages are retrieved from the
Application
instance byMessageFactory
. An application that creates its own custom messages must provide a class, such asMessageFactory
, that retrieves the messages from theApplication
instance. When creating your own application, you can simply copy theMessageFactory
class from the Duke's Bookstore application to your application.The
getMessage(FacesContext, String, Object)
method ofMessageFactory
takes aFacesContext
, a staticString
that represents the key into theProperties
file, and the format pattern as anObject
. The key corresponds to the static message ID in theFormatValidator
class:When the error message is displayed, the format pattern will be substituted for the
{0}
in the error message, which, in English, isCreating a Custom Tag
If you implemented a
Validator
interface rather than implementing a backing bean that performs the validation, you need to do one of the following:
- Allow the page author to specify the
Validator
implementation to use with thevalidator
tag. In this case, theValidator
implementation must define its own properties. Using a Custom Validator explains how to use thevalidator
tag.- Create a custom tag that provides attributes for configuring the properties of the validator from the page. Because the
Validator
implementation from the preceding section does not define its attributes, the application developer must create a custom tag so that the page author can define the format patterns in the tag.To create a custom tag, you need to do two things:
Using a Custom Validator explains how to use the custom validator tag on the page.
Writing the Tag Handler
The tag handler associated with a custom validator tag must extend the
ValidatorTag
class. This class is the base class for all custom tag handlers that createValidator
instances and register them on UI components. Thebookstore6/src/taglib/FormatValidatorTag
is the class that registers theFormatValidator
instance.The
FormatValidatorTag
tag handler class does the following:
- Sets the ID of the
Validator
by callingsuper.setValidatorId("FormatValidator")
.- Provides a set of accessor methods for each attribute defined on the tag.
- Implements the
createValidator
method of theValidatorTag
class. This method creates an instance of theValidator
and sets the range of values accepted by the validator.Here is the
createValidator
method fromFormatValidatorTag
:protected Validator createValidator() throws JspException { FormatValidator result = null; result = (FormatValidator) super.createValidator(); result.setFormatPatterns(formatPatterns); return result; }This method first calls
super.createValidator
to get a newValidator
and casts it toFormatValidator
.Next, the tag handler sets the
Validator
instance's attribute values to those supplied as the values of theformatPatterns
tag attribute. The handler gets the attribute values from the page via the accessor methods that correspond to the attributes.Writing the Tag Library Descriptor
To define a tag, you declare it in a tag library descriptor (TLD), which is an XML document that describes a tag library. A TLD contains information about a library and each tag contained in it. See Tag Library Descriptors for more information about TLDs.
The custom validator tag is defined in the
bookstore.tld
, located in<
INSTALL>
/j2eetutorial14/examples/web/bookstore6/web/
directory. It contains only one tag definition, forformatValidator
:<tag> <name>formatValidator</name> ... <tag-class>taglib.FormatValidatorTag</tag-class> <attribute> <name>formatPatterns</name> <required>true</required> <rtexprvalue>false</rtexprvalue> ... </attribute> </tag>The
name
element defines the name of the tag as it must be used in the page. Thetag-class
element defines the tag handler class. The attribute elements define each of the tag's attributes.
Download
FAQ History |
API
Search Feedback |
All of the material in The J2EE(TM) 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.