JSF Tutorial - JSF Custom Validator Example








We can create our own Custom validator in JSF.

The following list has the steps we can follow to create a custom validator in JSF.

  • Create a validator class by implementing javax.faces.validator.Validator interface.
  • Implement validate() method of above interface.
  • Use Annotation @FacesValidator to assign a unique id to the custom validator.




Example

The following code is from EmailValidator.java.

package com.java2s.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("com.java2s.common.EmailValidator")
public class EmailValidator implements Validator{

  private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\." +
      "[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*" +
      "(\\.[A-Za-z]{2,})$";

  private Pattern pattern;
  private Matcher matcher;
  
  public EmailValidator(){
      pattern = Pattern.compile(EMAIL_PATTERN);
  }
  
  @Override
  public void validate(FacesContext context, UIComponent component,
      Object value) throws ValidatorException {
    
    matcher = pattern.matcher(value.toString());
    if(!matcher.matches()){
      
      FacesMessage msg = 
        new FacesMessage("E-mail validation failed.", 
            "Invalid E-mail format.");
      msg.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ValidatorException(msg);

    }

  }

}

The following code is from demo.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:body>
    <h:form>
      <h:panelGrid columns="3">
        Enter your email :
        <h:inputText id="email" value="#{user.email}" 
          size="20" required="true" label="Email Address">
          <f:validator validatorId="com.java2s.common.EmailValidator" />
        </h:inputText>
        <h:message for="email" style="color:red" />
      </h:panelGrid>
      <h:commandButton value="Submit" action="result" />
    </h:form>
    </h:body>
</html>

The following code is from result.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"
      >
    <h:body>
      
      <h1>Custom validator in JSF 2.0</h1>
      
      <h:panelGrid columns="2">
      
        Email Address :  
        <h:outputText value="#{user.email}" />
        
      </h:panelGrid>
      
    </h:body>
</html>

The following code is from UserBean.java.

package com.java2s.common;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{
  
  private static final long serialVersionUID = 1L;
  
  String email;

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

}


Download Custom-Validator.zip





To RUN

Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.

After Tomcat finish starting, type the following URL in the browser address bar.

http://localhost:8080/simple-webapp/demo.xhtml