The Java EE 6 Tutorial, Volume I

Writing a Method to Perform Validation

Instead of implementing the Validator interface to perform validation for a component, you can include a method in a backing bean to take care of validating input for the component.

A backing bean method that performs validation must accept a FacesContext, the component whose data must be validated, and the data to be validated, just as the validate method of the Validator interface does. A component refers to the backing bean method by using its validator attribute. Only values of Input components or values of components that extend Input can be validated.

Here is an example of a backing bean method that validates user input:

public void validateEmail(FacesContext context,
     UIComponent toValidate, Object value) {
    String message = "";
    String email = (String) value;
    if (email.contains(’@’)) {
        message = CoffeeBreakBean.loadErrorMessage(context,
            new FacesMessage(message));

Let's take a closer look at the above code segment:

  1. The validateEmail method first gets the local value of the component.

  2. It then checks whether the @ character is contained in the value.

  3. If not, the method sets the component’s valid property to false.

  4. The method then loads the error message and queues it onto the FacesContext instance, associating the message with the component ID.

See Referencing a Method That Performs Validation for information on how a component tag references this method.