background image

Creating a Custom Validator

<< Implementing Action Listeners | Implementing the Validator Interface >>
<< Implementing Action Listeners | Implementing the Validator Interface >>

Creating a Custom Validator

"Registering an Action Listener on a Component" on page 360
explains how to register this
listener onto a component.
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" on page 307
, there
are two ways to implement validation code:
Implement a backing bean method that performs the validation.
Provide an implementation of the Validator interface to perform the validation.
"Writing a Method to Perform Validation" on page 406
explains how to implement a backing
bean method 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 Validator implementation, you can forgo
creating a custom tag and instead let the page author register the validator on a component
using the validator tag, as described in
"Using a Custom Validator" on page 375
.
You can also create a backing bean property that accepts and returns the Validator
implementation you create as described in
"Writing Properties Bound to Converters, Listeners,
or Validators" on page 389
. The page author can use the validator tag's binding attribute to
bind the Validator implementation to the backing bean property.
Usually, you will want to display an error message when data fails validation. You need to store
these error messages in resource bundle, as described in
"Creating a Resource Bundle" on
page 390
.
After creating the resource bundle, you have two ways to make the messages available to the
application. You can queue the error messages onto the FacesContext programmatically. Or,
you can have the application architect register the error messages using the application
configuration resource file, as explained in
"Registering Custom Error Messages" on page 448
.
The Duke's Bookstore application uses a general-purpose custom validator (called
tut-install/javaeetutorial5/examples/web/bookstore6/src/java/com/sun/bookstore6/validators/FormatValidator.j
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 the bookcashier.jsp page. Here is
the custom validator tag:
<bookstore:formatValidator
formatPatterns=
"9999999999999999|9999 9999 9999 9999|
9999-9999-9999-9999
"/>
Creating a Custom Validator
The Java EE 5 Tutorial · September 2007
398