About Custom JSF Validators

The standard validators supplied in the JavaServer Faces Reference Implementation provide common validation checks for numeric ranges and string lengths. If you need more complex validation rules and checks, you can implement your own validation code by either implementing a javax.faces.validator.Validator interface, or creating a bean method that performs the custom validation.

Implement Validator interface

It is beyond the scope of this topic to teach you how to implement the Validator interface. Briefly, in the custom implementation you define a method to override the validate method of the Validator interface. Use javax.faces.validator.ValidatorException to throw the appropriate exceptions and javax.faces.application.FacesMessage to generate the corresponding error messages.

You may choose to configure the validator's attributes in the implementation. If you do so, you do not have to create a custom tag for registering the validator on a component. If you choose not to configure the validator's attributes in the implementation, then you must create a custom tag, and provide in the implementation a set of accessor methods for any attributes on the tag. The second choice provides a way to configure the validator's attributes from the page during application development. For example, you might want to let the page author specify the format patterns that are allowed for an employee number input field.

In addition, if you wish to have configuration property values saved and restored with the view, your implementation must also implement StateHolder. For more information about the Validator interface, see the Javadoc for javax.faces.validator.Validator , or go to the java.sun.com web page
http://java.sun.com/j2ee/javaserverfaces/

To use a custom validator in your application (with or without a custom tag), you need to:

Create bean method

Creating a bean method for performing validation is a good way to provide a custom validator for use within a specific application because the method can access other instance fields of the class.

Like the validate method of the Validator interface, your bean method must accept a FacesContext, a UIComponent whose data is to be validated, and the data to be validated. To use a validation bean method on a component, use the validator attribute of the component to reference the method via a method binding expression.


Registering a Custom Converter or Validator in an Application
Registering a Custom Validator on a Component
Referencing a Bean Method That Performs Validation