JSF - Creating a Custom Validator

[Updated: Sep 11, 2017, Created: Sep 11, 2017]

This example shows how to create a custom validator in JSF. A validator checks the local value of the input component per predefined constraints. It does so, during the Process Validations phase of the request processing lifecycle. A validator must implement the javax.faces.validator.Validator interface. If validation fails, the validator typically creates a FacesMessage instance describing the problem, and throws ValidatorException. On validation failure lifecycle advances directly to the Render Response phase (skipping update model values and other phases) so that the page is rendered again with the error messages displayed.

Example

Creating and registering the Validator

@FacesValidator("phoneValidator")
public class PhoneValidator implements Validator {
  private static final Pattern PHONE_PATTERN = Pattern.compile("(\\d{3})-(\\d{3})-(\\d{4})");

  @Override
  public void validate(FacesContext context, UIComponent component,
                       Object value) throws ValidatorException {
      Matcher matcher = PHONE_PATTERN.matcher(value.toString());
      if (!matcher.matches()) {
          FacesMessage msg =
                  new FacesMessage("Invalid phone format",
                          String.format("invalid input: %s, The valid format regex: %s",
                                  value, PHONE_PATTERN.pattern()));
          msg.setSeverity(FacesMessage.SEVERITY_ERROR);
          throw new ValidatorException(msg);
      }
  }
}

JSF page

src/main/webapp/index.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
<h:head></h:head>
<h:body>
    <h2>JSF custom converter example</h2>
    <h:form>
        <h:panelGrid columns="3">
            <h:outputLabel for="ph" value="Phone: "/>
            <h:inputText id="ph" value="#{phoneBean.phone}">
                <f:validator validatorId="phoneValidator" />
            </h:inputText>
            <h:message for = "ph" style = "color:red" />
          <span></span>  <h:commandButton value="Submit" action="result.xhtml"/>
        </h:panelGrid>

        <div>
            phone:
            <h:outputText value = "#{phoneBean.phone}"/>
        </div>
    </h:form>
</h:body>
</html>

Managed Bean

@ManagedBean
@ViewScoped
public class PhoneBean {
  private String phone;

  public String getPhone() {
      return phone;
  }

  public void setPhone(String phone) {
      this.phone = phone;
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Submitting invalid value for phone number:

Submitting a valid value:

Example Project

Dependencies and Technologies Used :

  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • JDK 1.8
  • Maven 3.3.9

JSF Custom Validator Example Select All Download
  • custom-validator-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp

See Also