JavaServer Faces JSF Validation Tutorial: Error Handling in JSF

jsf-validators-jsf-validation
In continuation with my previous article on Creating JavaServer Faces JSF application in Eclipse, I am posting 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, created Error Messages during the life cycle of JSF and attached 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 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

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

f:validateDoubleRange : This tag checks the value of 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 restrict it within a specified range. The value must be of type java.lang.String.

f:validateLongRange : Checks is 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 bind checkUsername() method of userBean to component inputText. It is possible to bind more than one validators to one component.

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, Validator interface can be used.

Custom validation components using Validator interface

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. Validator interface provides a method validate () that needs to be implemented. 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 with any component using f:validator tag.

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

Note that in above code snippet, 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 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.

<< PREVIOUS: Tutorial: Creating JavaServer Faces JSF application in Eclipse.



25 Comments

  • John Dondapati 3 March, 2009, 3:33

    Hi,
    Useful article buddy. It would really help if you can put up a post on integrating Apache Shale with JSF. Thanks. Keep up the good work!

    Cheers,
    John

  • carbouserz 8 November, 2009, 19:17

    What’s up? Been reading for a while and just decided to write!

  • donato 17 November, 2009, 14:52

    Short but very well done tutorial. Thanxs

  • dan 29 November, 2009, 20:53

    THANKS. Very good

  • Faisal 24 February, 2010, 12:59

    Very useful and to the point hints in this tutorial. Thanks for this share.

  • Anurag 12 March, 2010, 10:07

    Thanks for the article. Real good one.

    • aurang 25 June, 2014, 17:35

      Nice work , keep it up ..

  • vinay 8 April, 2010, 9:05

    thanks buddy.

  • Ravi 8 July, 2010, 23:49

    Hi how to generate popup while displaying validation error. for example for inputtext required=true if i skip and press submit button i want to display h:message in popup is that possible in jsf2.0 . could u repsond this .

    Thanks inadvance.

    • Ezhil 5 April, 2011, 16:59

      Thanks for the tutorial. Very helpful for the beginners :)

  • Baychen 11 April, 2011, 20:03

    thx 4 the tutoial :))

  • Ahmed Abd El-Rasoul 27 April, 2011, 21:18

    Thanks , very good for the beginner :D

  • abhinav rao 1 September, 2011, 2:58

    Thanks for the article. good for the beginners…………

  • Ufuk 4 December, 2011, 16:59

    You’ve listed 4 type of validations but gave detail about only 3 of them… What about ‘Application Level Validation’ ?
    Thanks.

  • guna 24 April, 2012, 11:11

    if i use target attribute in commandLink tag here,will it display error message in current window ?(it will show error message in popup window)

  • SN 31 May, 2012, 18:55

    very informative article, really helped me

  • John 5 October, 2012, 22:47

    Searched for a short example, thanks!

  • salim 5 December, 2012, 4:45

    what if the entered email contains more than one ‘@’ !!!!
    the value will pass the validator !!!
    using a more accurate validation like regex is much more reliable !

  • subbareddy 20 March, 2013, 17:46

    Hi,
    I am new to primefaces. I want to use primefaces. Which jar files are mandatory & which link are available. Please tell me.

    Thanks & Regards
    Subbareddy

  • jagan 7 February, 2014, 16:15

    nice and easialy understandable

  • tommy jerax 20 February, 2014, 21:24

    after message show how i can remove it? i have a problem after submit, when user click back button , the form show validation message.

    Thaks

  • jayprakash 10 March, 2014, 17:58

    very good article for email validation in JSF.

  • PAUC AMARASINGHE 15 March, 2014, 15:09

    Thank you very much, very understandable article.

  • Brian Sutter 31 March, 2014, 23:02

    Thank you very much! Worked perfectly!

  • yesha 24 May, 2014, 22:49

    please post the code for validating the password and confirm password

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *