Viral Patel is a keen technology blogger and enthusiast. Working with a software company, he uses his leisure time to learn and explore emerging areas in tech world. His passion for technology has motivated him from creating an operating system to writing tutorials/articles on Java, JavaEE, Spring, Hibernate, Struts, jQuery, PHP. Visit the website http://viralpatel.net for a wide range of articles and tutorials on these topics. Viral has posted 13 posts at DZone. View Full User Profile

JSF Validation Tutorial: Error Handling in JSF

03.01.2009
| 112877 views |
  • submit to reddit
In a continuation of my previous article on Creating JavaServer Faces JSF application in Eclipse, I am posting the next article in the series. This time we will cover details about JSF Validation Model and Handling Errors in JSF.

JavaServer Faces technology supports a mechanism for validating the data of editable components. Each component in JavaServer Faces creates Error Messages during the life cycle of JSF and attaches them to FacesContext object. Hence each message is attached to a component in the component tree and the message is displayed into the view at the end of JSF life cycle.

Showing Error Messages on View

JSF provides different tags to handle and display messages on the view. There are two message tags in Sun’s reference implementation of JSF HTML library:

<h:message />
<h:messages />

h:messages is used to display all messages at once. You can place h:messages tag in start of your form. You may need to display only global messages using h:messages tag. For displaying only global messages set globleOnly attribute of h:messages to true.

<h:messages globalOnly="true" />

Use h:message to display message attached to one component. An attibute for=”" can be used to specify the id of a component whose error messages we need to display. h:message is used to display error message next to the component that generated the error. If more then one message is attached to that component, h:message will display the last message.

...
<h:inputText id="userName" value="#{userBean.userName}" />
<h:message for="userName" />
...

Each message can have a summary description and a detailed description. When using the h:message tag, the default is to show the detail message. When using the h:messages tag, the default is to display the summary descriptions. To change the defaults, modify the boolean showSummary and showDetail attributes.

<h:message for="userName" showSummary="true"/>
<h:messages showDetail="true"/>

You can also enable a component’s detail message to appear as a tooltip. To do so, set tooltip attribute of message tag to true. Note that for enabling this option, showDetail and showSummary must be set to true.

There are four forms of JSF validation:
1. Built-in validation components
2. Application level validations
3. Custom validation components using Validator interface
4. Validation methods in backing beans

Built-in validation components

Sun’s reference implementation of JSF provides some default validation components that can be leveraged to implement validation of any user input. The JSF core library provides tags to validate input. The following are a few tags that can be used to validate the input.

f:validateDoubleRange : This tag checks the value of a component within specified range. The value must be convertible to floating-point type or a floating-point itself.

f:validateLength : This tag checks the length of a value and restricts it within a specified range. The value must be of type java.lang.String.

f:validateLongRange : Checks if a component value is within a specified range. The value must be of numeric type or string convertible to a long.
Example:

<h:inputText id="Username" value="#{UserBean.userName}">
	<f:validateLength minimum="6" maximum="15"/>
</h:inputText>
....
<h:inputText id="Age" value="#{UserBean.age}">
	<f:validateLongRange minimum="1" maximum="120"/>
</h:inputText>

Validation using Backing Bean methods

A backing bean method can be used for doing validation of any input field. First we need to create the backing bean method that will get called during validation process. The signature of the method can be:

public void <METHOD_NAME> (FacesContext context, UIComponent component, Object value) { .. }

Once a backing bean method is ready we can bind it with a component using f:validator tag.

<h:inputText value="#{userBean.name}" validator="#{userBean.checkUsername}">
</h:inputText>

In above snippet, we have bound the checkUsername() method of userBean to the inputText component. It is possible to bind more than one validator to one component.

THe backing bean method of validation is easy to implement, but this method is specific for one application and may not be reused for different application. To create generic validators which can be used in different application, the Validator interface can be used.

Custom validation components using Validator interface

The Validator interface can be extended and a custom validator can be created which can be reused across different applications in JSF. To create a custom validator, we need to create a Java class that implements javax.faces.validator.Validator interface. The Validator interface provides a validate () method that needs to be implemented. The following is the signature of validate() method.

  
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
...
...
public void validate(FacesContext context, UIComponent component, Object value)
		throws ValidatorException {
}

Once the Validator is implemented, we need to register this validator in faces-config.xml file. To do so copy following code in faces-config.xml assuming that our validator class name is net.viralpatel.jsf.helloworld.EmailValidator.

<validator>
	<validator-id>emailValidator</validator-id>
	<validator-class>net.viralpatel.jsf.helloworld.EmailValidator</validator-class>
</validator>

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

<h:inputText id="Email" value="#{userBean.email}" required="true">
	<f:validator validatorId="emailValidator" />
</h:inputText>

Note that in the above code snippet, the validatorId attribute of f:validator tag points to the validator’s ID that is registered in faces-config.xml file.
For validating email address we can create a Validator class as:

  
package net.viralpatel.jsf.helloworld;

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 email = (String) value;

		if(!email.contains("@")) {
			FacesMessage message = new FacesMessage();
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			message.setSummary("Email is not valid.");
			message.setDetail("Email is not valid.");
			context.addMessage("userForm:Email", message);
			throw new ValidatorException(message);
		}
	}
}

Thus by using the JSF Validation framework, it is possible to validate user input easily. We saw different ways of validation in JSF: Default validators, backing bean methods and validation through validator interface.

Let me know your comments about this tutorial.

From http://viralpatel.net/blogs/

Published at DZone with permission of its author, Viral Patel.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Guillaume Jeudy replied on Mon, 2009/03/02 - 1:27pm

I would be interested about hearing what you have to propose on bean level validation? JSF 1.2 is severely lacking in that area and the provided JSF validator hooks are useful only for trivial field level validation.

Robin Bygrave replied on Mon, 2009/03/02 - 3:38pm

I agree with gjeudy... and am also very interested in how you propose/do cross field and conditional validation.

 


Sudhir Mongia replied on Mon, 2010/09/13 - 6:02am

You listed about four forms of JSF. But you have listed only three. There are four forms of JSF validation: 1. Built-in validation components 2. Application level validations 3. Custom validation components using Validator interface 4. Validation methods in backing beans What about Application level validations? Sudhir

Sudhir Kumar replied on Tue, 2011/06/14 - 9:28am

Hi, This is sudheer. it is good for learning jsf could you please provide me explanation for jsf tutorial and examples. i want tutorial for jsf please help me.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.