JSF - Creating a Custom Validator

[Last Updated: 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.


Creating and registering the Validator

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

  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()));
          throw new ValidatorException(msg);

JSF page


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns=""
    <h2>JSF custom converter example</h2>
        <h:panelGrid columns="3">
            <h:outputLabel for="ph" value="Phone: "/>
            <h:inputText id="ph" value="#{}">
                <f:validator validatorId="phoneValidator" />
            <h:message for = "ph" style = "color:red" />
          <span></span>  <h:commandButton value="Submit" action="result.xhtml"/>

            <h:outputText value = "#{}"/>

Managed Bean

public class PhoneBean {
  private String phone;

  public String getPhone() {
      return phone;

  public void setPhone(String phone) { = phone;

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

mvn tomcat7:run-war


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