JSF Validation Example Tutorial – validator tag, Custom Validator

Filed Under: JSF

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://xmlns.jcp.org/jsf/html"
	xmlns:f="http://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.

Comments

  1. Mohamed says:

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

  2. Sarafina says:

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

  3. Javier says:

    Thank you!

    Your post is very clear an easy to understand,

  4. Beanception says:

    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.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages