Tutorial

JSF Validation Example Tutorial - validator tag, Custom Validator

Published on August 3, 2022
Default avatar

By Pankaj

JSF Validation Example Tutorial - validator tag, Custom Validator

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

JSF validation model defines a set of standard classes for validating the UI components. The JSF library defines a group of core tags that corresponds to javax.faces.validator.Validator implementations. Apart from the standard error messages validation model allows us to define the custom validations. Validations in JSF can be categorized into Imperative and Declarative.

JSF Validation - Declarative Validator

The validations that are fired using JSF standard validators or Bean validators fall under declarative type. Examples for JSF standard validators are Length validator, Required validator etc… Consider an example for standard validator. Create mobile.xhtml as mobile.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:h="https://java.sun.com/jsf/html">
<h:head>
</h:head>
<h:body>
	<h3>Add Mobile Details</h3>
	<h:form>
		<h:panelGrid columns="3">
			<h:outputLabel for="mname">Mobile Name:</h:outputLabel>
			<h:inputText id="mname" required="true"
				requiredMessage="Mobile Name is mandatory"></h:inputText>
			<br>
			<br>

			<h:outputLabel for="color">Color:</h:outputLabel>
			<h:inputText id="color" required="true"></h:inputText>
			<br>
			<br>

			<h:outputLabel for="model">Model Number:</h:outputLabel>
			<h:inputText id="model"></h:inputText>
			<br>
			<br>

			<h:commandButton value="Submit"></h:commandButton>
		</h:panelGrid>
	</h:form>
</h:body>
</html>

Here we are setting the required attribute to true which makes the field mandatory and fires the custom message “value is required” for color field and user defined message for mobile name field as the message is specified in the requiredmessage attribute. Run the application and you will see the below output on pressing submit button. JSF Validation, JDF Validator

JSF Imperative validation

The standard validation messages would not be sufficient in all the cases and sometimes may require complex validations.Imperative validation allows users to do this by

  1. Firing the validation from the Bean method
  2. Use annotation @FacesValidator in the class during runtime

Firing the validation from the Bean method In this type of validation we write a method in the bean to validate the UIComponents and invoke this method from the jsf page through a validator attribute in the inputText tag. Now lets see consider an example of firing a validation from the Bean. mob.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:h="https://java.sun.com/jsf/html">
<h:head>
</h:head>
<h:body>
	<h3>Add Mobile Details</h3>
	<h:form>
		<h:outputLabel for="mno">Model Number:</h:outputLabel>
		<h:inputText id="mno" value="#{mobile.mno}" required="true" size="4"
			disabled="#{mobile.mno}" validator="#{mobile.validateModelNo}">
		</h:inputText>
		<h:commandButton value="Submit"></h:commandButton>
	</h:form>
</h:body>
</html>

In this page we are invoking the validateModelno method of the java bean in the validator tag attribute. Create Mobile.java as

package com.journaldev.jsf.bean;

import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class Mobile implements Serializable {

	private static final long serialVersionUID = -7250065889869767422L;

	// @NotNull(message="Please enter the model number")
	private String mno;

	public String getMno() {
		return mno;
	}

	public void setMno(String mno) {
		this.mno = mno;
	}

	public void validateModelNo(FacesContext context, UIComponent comp,
			Object value) {

		System.out.println("inside validate method");

		String mno = (String) value;

		if (mno.length() < 4) {
			((UIInput) comp).setValid(false);

			FacesMessage message = new FacesMessage(
					"Minimum length of model number is 4");
			context.addMessage(comp.getClientId(context), message);

		}

	}

}

Here we are checking for the length of the model no and if the length is less than 4 we are specifying the message as “Minimum length of model number is 4”. Now Run the application which produces the following output. JSF Validation Example

Using @FacesValidator in the Bean - Custom JSF Validator

In this method we use @FacesValidator annotation, specify the name for the validator and implement the Validator by overriding the validate method. mobvalidator.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"
	xmlns:h="https://xmlns.jcp.org/jsf/html"
	xmlns:f="https://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
	<h:form>
		<h3>Validation using Faces validator</h3>
		<h:outputLabel for="mno" value="Model Number: " />
		<h:inputText id="mno" value="#{mobileValidator.mno}">
		<f:validator validatorId="mobileValidator" />
		</h:inputText>
		<h:message for="mno" style="color:blue" />
		<p></p>
		<h:commandButton value="Submit"></h:commandButton>
	</h:form>
</h:body>
</html>

In this we are calling the custom validator named “mobileValidator” in the validatorId attribute of the <f:validator> tag. Create MobileValidator.java as

package com.journaldev.jsf.bean;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
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;

@ManagedBean
@SessionScoped
@FacesValidator("mobileValidator")
public class MobileValidator implements Validator {

	private String mno;

	public String getMno() {
		return mno;
	}

	public void setMno(String mno) {
		this.mno = mno;
	}

	int maximumlength = 6;

	public MobileValidator() {
	}

	@Override
	public void validate(FacesContext fc, UIComponent uic, Object obj)
			throws ValidatorException {

		String model = (String) obj;

		if (model.length() > 6) {
			FacesMessage msg = new FacesMessage(
					" Maximum Length of 6 is exceeded.Please enter values within range");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);

			throw new ValidatorException(msg);
		}

	}

}

Here we override the standard validate method and implement our own logic for validating the input fields. Run the application and see the output as shown below. JSF Validation Validator Finally below image shows the project structure. JSF Form Validation, Custom Validator You can download the project from below link and play around with it to learn more.

Download JSF Validation Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 13, 2018

use these tag after the tag of the component which you created validation for it

- Mohamed

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 11, 2018

    How do I style the error message that is being displayed? When I tried the code mentioned above, the error message displays in black.

    - Sarafina

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      January 25, 2017

      Thank you! Your post is very clear an easy to understand,

      - Javier

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 20, 2016

        I would personally make two different classes: · a backingbean with the form data with @ViewScoped · another for the Validator with @RequestScoped (no need to have the instance of the Validator all session long with @SessionScoped) Regards.

        - Beanception

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 22, 2015

          good +1

          - nice

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Get our biweekly newsletter

            Sign up for Infrastructure as a Newsletter.

            Hollie's Hub for Good

            Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

            Become a contributor

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            Welcome to the developer cloud

            DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

            Learn more
            DigitalOcean Cloud Control Panel