Tutorials  /  JavaScript

JSF Validation Example Tutorial

Ccentron Redaktion · March 2024 ·3 min read ·JavaScript, 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

Code
<?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 required="true"
				requiredMessage="Mobile Name is mandatory"></h:inputText>
			<br>
			<br>

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

			<h:outputLabel for="model">Model Number:</h:outputLabel>
			<h:inputText></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.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

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

Code
<?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 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

Go
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

Code
<?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 value="#{mobileValidator.mno}">
		<f:validator validatorId="mobileValidator" />
		</h:inputText>
		<h:message for="mno" />
		<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

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

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren