On this Page

JSF Custom validators example

Custom validators  are used when we need to apply custom validation logic on a field’s input value on our form during submission but  before processing on the controller method.

We achieve this by implementing the javax.faces.validator.Validator interface.

Lets implement a simple validation on our admission application. We will only admit students between the ages of 10 to 18 years, above 18 will be considered too old for our school (so as to speak).

We shall achieve this by taking the current date and substracting the date of birth submitted.The difference gives the number of years.If this is between 10 to 18 years,that will be considered valid age,outside this range we shall either display ‘Too young for our school.Min admission age is 10 years’ or ‘Above age for our school.Max admission age is 18 years’ error messages.

We implement custom validators by implementing the Validator interface and overriding the  public void validate(FacesContext fc, UIComponent uic, Object object) throws ValidatorException  method.

The object instance represents the passed in value which we type cast to the data type applicable to the input field we are validating.e.g if we are validating a string input,we type cast to String,if working with a Date input we type cast to a  Date instance.

If validaton fails,we throw ValidatorException  .We can incorporate a custom message by passing in an instance of FacesMessage .

Our Age validator is implemented as shown below.

package com.example.jsfform.validators;

import java.util.Calendar;

import static java.util.Calendar.YEAR;

import java.util.Date;

import java.util.Locale;

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;

 

/**

 *

 * @author hp

 */

@FacesValidator(value = "age.validator")

public class AgeValidator implements Validator {

 

    @Override

    public void validate(FacesContext fc, UIComponent uic, Object object) throws ValidatorException {

        FacesMessage message = null;

        Date dob = (Date) object;

        int dobYear = getCalendar(dob).get(YEAR);

        int currentYear = getCalendar(new Date(System.currentTimeMillis())).get(YEAR);

 

        boolean invalidAge = false;

        try {

            int age = currentYear - dobYear;

            if (age < 10) {

                message = new FacesMessage("Too young for our school.Min admission age is 10 years");

                invalidAge = true;

            } else if (age > 18) {

                message = new FacesMessage("Above age for our school.Max admission age is 18 years");

                invalidAge = true;

            }

            if (invalidAge) {

                message.setSeverity(FacesMessage.SEVERITY_ERROR);

                throw new ValidatorException(message);

            }

        } catch (Exception ex) {

            throw new ValidatorException(new FacesMessage(ex.getMessage()));

        }

    }

 

    private Calendar getCalendar(Date date) {

        Calendar cal = Calendar.getInstance(Locale.US);

        cal.setTime(date);

        return cal;

    }

}

We then plug in the custom validator in our input fields as below

<h:inputText value="#{admissionController.dateOfBirth}" id="dob"  required="true" requiredMessage="Date of birth required">

                <f:convertDateTime pattern="MM/dd/yyyy" />

                <f:validator validatorId="age.validator"/>

 </h:inputText>

When an invalid age,in our case any one above 18 years by inputting a date like 12/15/2000(MM/dd/yyyy),we get an error screen as shown below when we submit the form.

 

 

In addition ,when we pass another date of birth whereby the age is < 10 years(invalid input),we get below error screen as well

 

 

For valid input(between 10 and 18 years),we get below success screen

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.