JSF 2 custom validation – the email validation example

Today’s topic is JSF 2 custom validation. We are going to show you how to create and use a custom JSF 2 validator – the email address validator. Our sample application is consists of a simple form which takes email data. Email data is being validated by the JSF 2 validation mechanisms – custom EmailValidator class.
Our sample application looks like this:

JSF 2 custom validation - Email validation OK

JSF 2 custom validation – Email validation OK

JSF 2 custom validation - Email validation ERROR

JSF 2 custom validation – Email validation ERROR

This project was developed using the Eclipse IDE. To find out how to configure your development environment please refer to our earlier tutorials:
Maven 3 installation and configuration
Maven 3 Eclipse plugin setup
To see how to create a base project that was used in this tutorial please visit our earlier tutorial and follow the 7 steps listed there – Creating Maven 3 WebApp project.

The application project structure looks like this:

JSF 2 custom validation - sample Eclipse project structure

JSF 2 custom validation – sample Eclipse project structure


Here is project’s pom.xml file. Since we are using JBoss AS 7.x to run this application all the JSF2 artifacts are marked as provided. You don’t need them in the resulting WAR archive. JBoss comes bundled with JSF 2 implementation. Today all the popular JEE Application servers like WebLogic, WebSphere, Glassfish etc. comes bundled with the JSF 2 implementation.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <!-- JSF 2 API -->
	<!-- JSF 2 Implementation -->


You need to configure JSF2 in your web.xml file. JSF2 is implemented as a Servlet which processes URL in your application, in our case we map every URL that ends with *.xhtml to the Faces Servlet.

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

	<display-name>JSF 2 Form Email Validation example</display-name>
	<!-- The welcome page -->

	<!-- Start JSF -->
		<servlet-name>Faces Servlet</servlet-name>

	<!-- JSF URL mapping -->
		<servlet-name>Faces Servlet</servlet-name>



This is a simple JSF 2 bean which is indicated with the @ManagedBean. This class has the email attribute which is set through the http form. The submit() method is mapped as a form action.
The important thing to mention here is that the submit() method is going to be called by the JSF 2 framework only when the email address entered in the form is valid.

package com.itcuties.validation.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

public class EmailBean {

	private String email;

	public void submit() {
		System.out.println("EmailBean:: received valid email: " + email);
		// Set the message here
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Email is OK", "ok");  
		FacesContext.getCurrentInstance().addMessage(null, msg);
	public String getEmail() {
		return email;

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


This is the main class of this tutorial. This class implements the validation logic, it checks if the email address is valid or not.
To write your own JSF2 custom validation class all you need to do is implementing the javax.faces.validator.Validator interface. You need to implement the validate method and annotated your class with the @FacesValidator annotation providing the validator id which you are going to use in the view. The idea is that if something is wrong with the validated value the javax.faces.validator.ValidatorException needs to be thrown. Take a look at our example which is using Java Regex mechanisms which we have discussed in our earlier tutorial – Java Regular Expression

package com.itcuties.validation.validators;

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;

public class EmailValidator implements Validator {

	private final static String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	private final static Pattern EMAIL_COMPILED_PATTERN = Pattern.compile(EMAIL_PATTERN);
	 * Validate method.
	public void validate(FacesContext fc, UIComponent c, Object o) throws ValidatorException {
		// No value is not ok
		if (o == null || "".equals((String)o)) {
			FacesMessage msg = new FacesMessage("No email value!", "Email Validation Error");
			throw new ValidatorException(msg);
		// The email matcher
		Matcher matcher = EMAIL_COMPILED_PATTERN.matcher((String)o);
		if (!matcher.matches()) {	// Email doesn't match
			FacesMessage msg = new FacesMessage("Invalid email value!", "Email Validation Error");
			throw new ValidatorException(msg);


Here is our sample view. It consists of the form, an inputText and a button component. If you want to validate a field just add a f:validator tag to it providing validator id.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="http://www.w3.org/1999/xhtml"
        <title>Email Validation Form</title>
    	<h3>Email Validation Form</h3>
    	   <h:inputText value="#{emailBean.email}">
    	   		<f:validator validatorId="emailValidator" />
    	   <h:commandButton id="button" value="Submit and Validate" action="#{emailBean.submit}" />
    	   <h:messages />

Running the application

To build this code you need to call the mvn package command. As a result the validation.war package gets created in the target directory of your project. Deploy the WAR package on the application server. As mentioned before, the application server you are deploying your application to has to have a JSF implementation in it’s classpath. Using JBoss, WebLogic, WebSphere, Glassfish or any other application platform that comes bundled with the JSF 2 implementation is recommended.

Download this sample code here.

This code is available on our GitHub repository as well.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>