JSF Validation Tutorial

As you already aware, everything in JSF is governed by JSF life cycle. In our JSF Life Cycle tutorial we have discussed where and how JSF validation will happen.

Validation is 3rd phase in life cycle. Any validation error at this stage causes the control to jump directly to the "Render Response" phase i.e. processing of Update Model Value and Invoke Application is skipped.

There are four ways to validate data in JSF Application.


1. JSF supplied standard validators :

If you are using JSF supplied standard validators there is no need to write any code for validation logic. You need to use the standard validator tag of your choice inside a tag that represents a component of type UIInput (or a subclass of UIInput) and provide the necessary constraints. Let’s look at the JSF supplied standard validators in details.




LengthValidator (f:validateLength ) :

This tag will Check whether the length of a value is within a specified range.The value must be of type java.lang.String.

Minimum – The minimum acceptable number of characters.
Maximum – The maximum acceptable number of characters.

Example :

<h:inputtext id="name" value="#{UserBean.name}">
<f:validatelength minimum="6" maximum="15"/>
</h:inputtext>

LongRangeValidator (f:validateLongRange ) :

Checks whether the value of a component is within a certain range.The value must be of numeric type or string convertible to a long. The validator will attempt to convert the number to a Java long primitive. If minimum and maximum attributes are used the validator will ensure that the value entered is within the minimum and maximum range. If the minimum and maximum attribute are omitted then the validator ensures that the value is numeric.

Example :

<h:inputtext id="age" value="#{EmployeeBean.age}">
<f:validatelongrange minimum="1" maximum="59"/>
</h:inputtext>

DoubleRangeValidator (f:validateDoubleRange) :

This tag will check whether the value of a component is within a certain range. The value must be numeric or convertible to a numeric value. The validator will a convert the number into double type primitive value.

If minimum and maximum attributes are used the validator will ensure that the value entered is within the minimum and maximum range. If the minimum and maximum attribute are omitted then the validator only ensures that the value is numeric.

Example :

<h:inputtext id="leave" value="#{EmployeeBean.leave}">
<f:validatedoublerange minimum="-90" maximum="90"/>
</h:inputtext>

2 : Validation using Backing Bean methods :

A backing bean method can be used for doing validation of any input field.The JSF input component comes with a way you can bind a backing bean method to perform pure validation.Example is given below.

JSP File

<h:inputText value="#{bean.age}" validator="#{bean.validateAge}"/> 

Method inside Backing Bean

public void validateAge(FacesContext context, 
                          UIComponent inputComponent,
                          Object value) {
    // do your business validation
    ...
}

In this approach backing bean method must be the same method signature as the JSF Page.

One advantage of this option is that it provides a structure to group all the validation logic in a backing bean but this method is specific for one application and may not be reused for different application.


3 : JSF Custom validation components using Validator interface

In real time scenario JSF built in validation is not sufficient for the component value.You need to create your own validator. For example, you can create email validator to validate the email text entered by the user i.e. whether the email id is in correct format or not?

Using custom validator you will be able to display your own validation error message.

There are four steps for the implementation of JSF custom validation which is mentioned below.

  1. Create a class that implements the Validator interface
  2. Implement the validate() method
  3. Register your custom validator in the faces.config.xml file
  4. Use the <f:validator/> tag in your JSP's



Step 1 : Implement the Validator interface

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.

 package com.javawebtutor.jsf;
 
 public class EmailValidator implements Validator{
        ...
    }

Step 2 : Implement the validate() method

Implement the validation logic inside validate() method of Validator class

 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 3 : Register the Validator in the faces.config.xml

Once the Validator is implemented, we need to register this validator in faces-config.xml file.

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

Step 3 : Register the Validator in the faces.config.xml

Once the Validator is implemented, we need to register this validator in faces-config.xml file.

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

Step 4 : Use the Tag in your JSP

Bind the validator with any component using f:validator tag

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

In the avove code validatorId attribute of f:validator tag points to the validator's ID that is registered in faces-config.xml file.

In next Article we will discuss how to create JSF validation example using eclipse IDE.





comments powered by Disqus