Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

JSF Validation Example 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 submit button.

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

  • Firing the validation from the Bean method
  • 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.

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 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.

Start Your Cloud Journey Today with Our Free Trial!

Dive into the world of cloud computing with our exclusive free trial offer. Experience the power, flexibility, and scalability of our cloud solutions firsthand.

Try for free!