The Java EE 5 Tutorial

Using a Custom Validator

To register a custom validator on a component, you must do one of the following:

Here is the custom formatValidator tag from the ccno field on the bookcashier.jsp page of the Duke’s Bookstore application:

<h:inputText id="ccno" size="19"
    ...
    required="true">
    <bookstore:formatValidator
         formatPatterns="9999999999999999|9999 9999 9999 9999|
        9999-9999-9999-9999" />
</h:inputText>
<h:message styleClass="validationMessage"  for="ccno"/>

This tag validates the input of the ccno field against the patterns defined by the page author in the formatPatterns attribute.

You can use the same custom validator for any similar component by simply nesting the custom validator tag within the component tag.

Creating a Custom Validator describes how to create the custom validator and its custom tag.

If the application developer who created the custom validator prefers to configure the attributes in the Validator implementation rather than allow the page author to configure the attributes from the page, the developer will not create a custom tag for use with the validator.

    In this case, the page author must nest the validator tag inside the tag of the component whose data needs to be validated. Then the page author needs to do one of the following:

  1. Set the validator tag’s validatorId attribute to the ID of the validator that is defined in the application configuration resource file. Registering a Custom Validator explains how to configure the validator in the application configuration resource file.

  2. Bind the custom Validator implementation to a backing bean property using the validator tag’s binding attribute, as described in Binding Converters, Listeners, and Validators to Backing Bean Properties.

The following tag registers a hypothetical validator on a component using a validator tag and references the ID of the validator:

<h:inputText id="name" value="#{CustomerBean.name}"
            size="10" ... >
    <f:validator validatorId="customValidator" />
    ...
</h:inputText>