Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
21 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
aboalfazl
5 years ago

Thank you so much

Arpit
7 years ago

thanks … i’m really very grateful for this article.

David
7 years ago

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 🙂

Naveen
8 years ago

Hi,
in this example the error message hard coded in java, how to customize the error message using properties message bundle.

Daniel
8 years ago

I’m learning Java and I have to thank you a milion times !
Great site !

nits
9 years ago

Thanks

??????? ???????
9 years ago

ru: ???????!
en: Thanks!

Cezar Cruz
10 years ago

Works for me! Thanks!

Sahil
10 years ago

Each time I try it, a new error message gets added to the popup instead of just showing it once. Any idea why?

Oppa
11 years ago

Valeu demais!
thanks man!

balu
11 years ago

issue got fixed.small mistake from my side, forgot to update the message on ajax request.

balu
11 years ago

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"/>
balu
11 years ago

Validation working but message is not displaying if required=”false” for email field.

Please find the code snippet below

Amin Oruji
11 years ago

I love you man.

Chris
11 years ago

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!!

Deepak
11 years ago

Really very good blog. Thanks

Aditya
11 years ago

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.

Lumia
12 years ago

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)
megan
12 years ago
Reply to  Lumia

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

megan
12 years ago
Reply to  Lumia

I am getting the same! using JSF 2.0 with primefaces

Sreekanth
13 years ago

Thanks for the tip.I started with JSF and this is a nice one.