The Java EE 6 Tutorial

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 UIInput components or values of components that extend UIInput 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('@')) {
        ((UIInput)toValidate).setValid(false);
        message = CoffeeBreakBean.loadErrorMessage(context,
            CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME,
            "EMailError");
        context.addMessage(toValidate.getClientId(context),
            new FacesMessage(message));
    }
}

    Take a closer look at the preceding code segment:

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

  2. The method 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.