Custom validator in JSF 2.0

In this article, we will show you how to create a custom validator in JSF 2.0

Steps

  1. Create a validator class by implements javax.faces.validator.Validator interface.
  2. Override validate() method.
  3. Assign an unique validator ID via @FacesValidator annotation.
  4. Reference custom validator class to JSF component via f:validator tag.

A detail guide to create a custom validator name “EmailValidator” – to validate email address via Java regular expression.

1. Folder Structure

Directory structure of this project.

jsf2-custom-validator-folder

2. Validator class

Create a custom validator class and implements javax.faces.validator.Validator interface.


package com.mkyong;

import javax.faces.validator.Validator;
public class EmailValidator implements Validator{
	//...
}

Overrides the validate() method.


public class EmailValidator implements Validator{

	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		//...
	}
}

Assign an unique validator ID with @FacesValidator.


package com.mkyong;

import javax.faces.validator.Validator;

@FacesValidator("com.mkyong.EmailValidator")
public class EmailValidator implements Validator{
	//...
}

See a full custom validator class :

EmailValidator.java

package com.mkyong;

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.mkyong.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);

		}

	}
}

Above is a custom validator class, with id com.mkyong.EmailValidator. If email is invalid, returns FacesMessage error message.

Note
For detail explanation about the email regular expression pattern, please refer to this “Validate E-mail with Java regular expression” article.

3. Managed Bean

A normal managed bean named “user”, nothing special here.


package com.mkyong;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{
	
	String email;

	public String getEmail() {
		return email;
	}

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

}

4. JSF Page

Reference above custom validator to JSF component via “validatorId” attribute in f:validator tag.

Spring DI into JSF custom validator
If you need @Autowired into JSF custom validator, uses binding, instead of validatorId. Read this post – Spring @Autowired into JSF custom validator.
default.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>
    	
    <h1>Custom validator in JSF 2.0</h1>
		
	  <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.mkyong.EmailValidator" />
			
		  </h:inputText>
				
		  <h:message for="email" style="color:red" />
			
		</h:panelGrid>
			
		<h:commandButton value="Submit" action="result" />
			
	   </h:form>
	
    </h:body>
</html>
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>

5. Demo

Validates email address via custom validator, if email address is invalid, return a error message.

jsf2-custom-validator-example

Download Source Code

Download It – JSF-2-Custom-Validator-Example (10KB)

References

  1. Email validation with Java Regex
  2. Custom converter in JSF 2.0

21 comments on “Custom validator in JSF 2.0

  1. Thanks man! Your tutorials are very easy to understand, everything is clear and everything works fine. I’ll visit your site every day from now ๐Ÿ™‚

  2. Validation working but message is not displaying if required=โ€falseโ€ for email field.

    Please find the code snippet below

    <p:inputText autocomplete="off"  id="emailId" value="#{backingBean.emailID}" >
    <f:validator validatorId="ldapmanager.EmailValidator"/>
    </p:inputText>
    <p:message id="errEmailId" for="emailId"/>
    
  3. Thank you for your small tutorial. Each time I’m looking quickly for something in JSF 2, you always show up first in Google and I found what I search. Continue your great works!!

  4. I have a rich:datatable. I want to validate mandatory input fields in table. I want to show only one message for all mandatory field ie “please give some value for mandatory fields”.

    Please tell me how to achieve this.

  5. Hello sir i tried with same code for my application but i m getting error:

    javax.servlet.ServletException: Expression Error: Named Object: checkemail not found.
    	javax.faces.webapp.FacesServlet.service(FacesServlet.java:422)
    1. I think you will find it is the

      @FacesValidator(“com.mkyong.EmailValidator”)

      line -it must point to the correct package that contains your validator!

      megan

Leave a Comment

Your email address will not be published. Required fields are marked *