Jsf custom validator example

Let us discuss how to create custom validator in JSF with example.

Steps to create custom validator in JSF:

1. First create a validator class by implementing javax.faces.validator.Validator interface
2. Override validate() method of above interface.
3. Assign a unique validator ID to the custom validator by using @FacesValidator annotation.
4. Use custom validator class to JSF component via f:validator tag.

Example:

test.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>
		<title>JSF custom validator example.</title>
	</h:head>
    <h:body>
    	<h2>JSF custom validator example.</h2>
 
    	<h:form>
    	   <h:inputText id="emailId" label="Email: " 
    	     value="#{test.email}" required="true">
    	     <f:validator validatorId=
    	       "com.w3schools.business.EmailValidator" />
    	   </h:inputText>
    	   <br/>
    	   <h:message for="emailId" style="color:red" />
    	   <br/>
    	   <h:commandButton value="Submit" action="success"/>  
    	</h:form>
 
    </h:body>
 
</html>

Test.java

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
/**
 * Managed bean.
 * @author w3schools
 */
@ManagedBean(name="test")
@SessionScoped
public class Test {
	private String email;
 
	public String getEmail() {
		return email;
	}
 
	public void setEmail(String email) {
		this.email = email;
	}
 
}

EmailValidator.java

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.w3schools.business.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);
  }
 
  public void validate(FacesContext context, UIComponent component,
      Object value) throws ValidatorException {    
    matcher = pattern.matcher(value.toString());
    if(!matcher.matches()){      
      FacesMessage msg = 
        new FacesMessage("Email validation failed.", 
            "Invalid email format.");
      msg.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ValidatorException(msg);
    }
  }
}

welcome.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>
		<title>JSF custom validator example.</title>
	</h:head>
    <h:body>
    	<h2>JSF custom validator example.</h2> 
    	<h3>Email: <h:outputText value="#{test.email}"/></h3> 	
    </h:body>
 
</html>

faces-config.xml

<?xml version="1.0" encoding="windows-1252"?>
<faces-config version="2.0" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xi="http://www.w3.org/2001/XInclude" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
 
</faces-config>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    	xmlns="http://java.sun.com/xml/ns/javaee" 
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 
    <servlet>
        <servlet-name>faces</servlet-name>
        <servlet-class>
         javax.faces.webapp.FacesServlet
	<servlet-mapping>
        <servlet-name>faces</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
 
</web-app>

URL:

http://localhost:7001/JSFExample37/faces/test.xhtml

Output:

JSF example37-1
 
Enter value.
JSF example37-2
 
Click Submit button.
JSF example37-3
 
Download this example.