JSF Custom Validation Example in Eclipse

In this example we are going to create an email validator which will validate the email id entered by the user.

There are four Steps to create Custom validator in JSF.All Steps are mentioned below.

  1. Create a class that implements the javax.faces.validator.Validator interface.
  2. Implement the validate() method (defined in Validator interface).
  3. Register this validator in the configuration file faces-config.xml.
  4. Use this validator by <f:validator/> tag in the JSP page. Use <h:message> tag in the jsp page to display the error message.

In this example we are going to create an email validator which will validate the email id entered by the user.

There are four Steps to create Custom validator in JSF.All Steps are mentioned below.

  1. Create a class that implements the javax.faces.validator.Validator interface.
  2. Implement the validate() method (defined in Validator interface).
  3. Register this validator in the configuration file faces-config.xml.
  4. Use this validator by <f:validator/> tag in the JSP page. Use <h:message> tag in the jsp page to display the error message.






Directory Structure Of Project

Directory Structure of project is shown below:

JSF Validation Example


Tools used :

  1. JSF 1.2
  2. Eclipse
  3. JDK 1.6
  4. Tomcat 6.0

Note:-If you have no idea about how to create JSF Application in eclipse then it is strongly recommended to complete Creating JavaServer Faces Application In Eclipse Tutorial before starting of this Project.

Step 1: Create Dynamic Web project

Open Eclipse and go to File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.

JSF Example


Provide the name of the project as CustomValidator . Once this is done, select the target runtime environment as Apache Tomcat v6.0. This is to run the project inside Eclipse environment. In configuration select JavaServer Faces v1.2 Project and press Next -> Next -> Next.

JSF validation Example

In next screen select Disable Library Configuration from drop down and click Finish.

JSF validation Example


Step 2: Add jar files to build path of the project

Copy all the required jar files shown bellow to the lib folder of the project directory and add all jar files to the build path of the project.

JSF validation Example


Step 3: Create JSP files

Create two JSP files: index.jsp and success.jsp in WebContent folder.The login.jsp prompts the user to enter his/her details.We are validating the email id using our custom email validator.After successful validation user will be redirected to success.jsp page.In case of any data validation error message will be shown in the red color and it will ask to correct the data before form submission.

login.jsp

<%@ page contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<f:view>
	<html>
<head>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<title><h:outputText value="#{msg.title}" /></title>
</head>
<body bgcolor="silver">
	<h:form>
		<h1>
			<h:outputText value="#{msg.employee_info}" />
		</h1>
		<h:panelGrid columns="2">
			<h:outputText value="#{msg.name}" />
			<h:inputText id="name" label="#{msg.name}" value="#{employee.name}"
				required="true">
			</h:inputText>

			<h:outputText value="#{msg.phone}" />
			<h:inputText id="phone" label="#{msg.phone}"
				value="#{employee.phoneNumber}" required="true">
			</h:inputText>

			<h:outputText value="#{msg.email}" />
			<h:inputText id="email" label="#{msg.email}"
				value="#{employee.email}" required="true">
				<f:validator validatorId="emailvalidator" />
			</h:inputText>
			<h:message for="email" styleClass="errormsg" />

		</h:panelGrid>
		<h:commandButton value="Submit" action="submit" />

	</h:form>
</body>
	</html>
</f:view>


success.jsp

<%@ page contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<f:view>
	<html>
<head>
<title><h:outputText value="#{msg.title}" /></title>
</head>
<body bgcolor="silver">
	<h:form>
		<h1>
			<h:outputText value="#{msg.employee_info}" />
		</h1>
		<h:panelGrid columns="2">
			<h:outputText value="#{msg.name}" />
			<h:outputText value="#{employee.name}" />
			<h:outputText value="#{msg.phone}" />
			<h:outputText value="#{employee.phoneNumber}" />
			<h:outputText value="#{msg.email}" />
			<h:outputText value="#{employee.email}" />

		</h:panelGrid>
		<h:commandButton value="Back" action="back" />
	</h:form>
</body>
	</html>
</f:view>

Step 4 : Create properties file :

Create a package com.jwt.jsf.properties inside src/main/resources folder and create a properties file messages.properties inside this package and add following code into this.These key values will used in JSP pages for displaying text and message.

messages.properties

title=Sample Application to Test JSF built in validation
title=Sample Application to test Custom Validation
employee_info=Employee Information 
name=Name
phone=Phone Number
employee_info=Employee Details
email=Email ID


Step 5 : Create CSS File :

Our requirement is in case of any validation error we need to display the error message in Red color. For this we need to create one css file. We created style.css in which one css class errormsg is created for this purpose.

In login.jsp we added below code to display the error message.

<h:message for="email" styleClass="errormsg" />

In the above code "errormsg" is css class name.

Create a folder inside WebContent and provide the name of the folder as css.In this folder create a css file and name it to style.css and add below line of code into this file.

.errormsg {
   color:red; 
}

We need to provide the path of css in our jsp pages. We need to add below line of code to import css in the jsp pages.

<link href="css/style.css" rel="stylesheet" type="text/css" />


Step 6 : Create JSF Managed Bean

A Managed Bean is a regular Java Bean class, registered with JSF. In other words, Managed Bean is a java bean, managed by the JSF framework.From JSF 2.0 and onwards, we can declare a managed bean, just by using the annotation @ManagedBean.

Create a java class EmployeeBean inside "com.javawebtutor.jsf.bean" package and add bellow line of code into this class.

EmployeeBean.java

package com.javawebtutor.jsf.bean;

public class EmployeeBean {
	private String name;
	private String phoneNumber;
	private String email;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public String getEmail() {
		return email;
	}

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

}

Step 7 : Create Validator Class :

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

EmailValidator.java

package com.javawebtutor.jsf.validator;

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.Validator;
import javax.faces.validator.ValidatorException;

public class EmailValidator implements Validator {

	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String enteredEmail = (String) value;
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(enteredEmail);
		boolean matchFound = m.matches();
		if (!matchFound) {
			FacesMessage message = new FacesMessage();
			message.setSummary("Invalid Email ID.");
			throw new ValidatorException(message);
		}
	}
}

Step 8 : Update Configuration File(faces-config.xml)

Jsf looks for faces-config.xml in classpath and loads the configuration defined from here. Here we have defined managed bean (the backing bean), and navigation rule.Open faces-config.xml from WebContent -> WEB-INF folder and following code into this file.

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<faces-config 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-facesconfig_1_2.xsd"
	version="1.2">
	<navigation-rule>
		<from-view-id>/login.jsp</from-view-id>
		<navigation-case>
			<from-outcome>submit</from-outcome>
			<to-view-id>/success.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

	<navigation-rule>
		<navigation-case>
			<from-outcome>back</from-outcome>
			<to-view-id>/login.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

	<managed-bean>
		<managed-bean-name>employee</managed-bean-name>
		<managed-bean-class>com.javawebtutor.jsf.bean.EmployeeBean</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
	</managed-bean>

	<application>
		<resource-bundle>
			<base-name>com.javawebtutor.jsf.properties.messages</base-name>
			<var>msg</var>
		</resource-bundle>
	</application>

	<validator>
		<validator-id>emailvalidator</validator-id>
		<validator-class>com.javawebtutor.jsf.validator.EmailValidator</validator-class>
	</validator>
</faces-config>

We registered the validator in faces-config.xml file. We added below line of code into faces-config.xml file.

<validator>
		<validator-id>emailvalidator</validator-id>
		<validator-class>com.javawebtutor.jsf.validator.EmailValidator</validator-class>
	</validator>

We can bind this validator to any component using f:validator tag.

<h:inputText id="email" label="#{msg.email}"
value="#{employee.email}" required="true">
<f:validator validatorId="emailvalidator" />
</h:inputText>

Step 8 : Update web.xml

In this step we will configure JSF via the web.xml file which is found under src/main/webapp/WEB-INF.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>faces/login.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Output :

1. index page

JSF Validation Example

2. when Form is processed without any entry

JSF Validation Example

2. when email id is not valid

JSF Validation Example

3. When email is Valid

JSF Validation Example



You can download the source code of the example by clicking on the Download link below.

Source+lib (Developed in Eclipse) : Download




comments powered by Disqus