JSF Custom Validator

In Jsf we can create our own custom validator by implementing validator interface and override its validate method.

Example:

index.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"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:body>

<h3>JSF CustomValidators example</h3>

<h:form>
    Enter Name: 
<h:inputText id="name" value="#{user.name}" size="20"
label="name">
<f:validateLength minimum="5" maximum="8" />
</h:inputText>
<h:message for="name" style="color:red" />
<br/>
Enter Place: 
<h:inputText id="place" value="#{user.place}" size="20"
label="place" >
<f:validateRequired />
</h:inputText>
<h:message for="place" style="color:red" />
<br/>
 
Enter Age:
<h:inputText id="age" value="#{user.age}" 
         label="age" >
         <f:validateLongRange minimum="30" maximum="100" />
      </h:inputText>
      <h:message for="age" style="color:red" />
      <br/>
      Enter Salary:
      <h:inputText id="salary" value="#{user.salary}" 
         label="salary" >
         <f:validateDoubleRange minimum="50000.00" maximum="1000000.00" />
      </h:inputText>
      <h:message for="salary" style="color:red" />
      <br/>
      Enter password:
<h:inputSecret id="password" value="#{user.password}" 
         label="password" >
    <f:validateRegex pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})" />
      </h:inputSecret>
<h:message for="password" style="color:red" />
<br/>
Enter Email:
<h:inputText id="email" value="#{user.email}" 
         label="email" >
         <f:validator validatorId="com.javasafari.EmailValidator" />
      </h:inputText>
<h:message for="email" style="color:red" />
<br/>
<h:commandButton value="Submit" action="output" />
</h:form>

</h:body>
</html>

User Bean

package in.gov.tds.bean;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class User implements Serializable{
 
/**
* 
*/
private static final long serialVersionUID = 1L;
String name;
int age;
double salary;
String password;
String place;
String email;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the salary
*/
public double getSalary() {
return salary;
}
/**
* @param salary the salary to set
*/
public void setSalary(double salary) {
this.salary = salary;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the place
*/
public String getPlace() {
return place;
}
/**
* @param place the place to set
*/
public void setPlace(String place) {
this.place = place;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
}

Email Validator:

package com.javasafari;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

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;

@FacesValidator("com.javasafari.EmailValidator")
public class EmailValidator implements Validator {
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\."
+ "[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\.[A-Za-z0-9]+)*"
+ "(\.[A-Za-z]{2,})$";

private Pattern pattern;
private Matcher matcher;

public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}

@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {

matcher = pattern.matcher(value.toString());
if (!matcher.matches()) {

FacesMessage msg = new FacesMessage("E-mail Validation failed.",
"Invalid E-mail Address");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);

}

}
}

OutputPage:

<?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"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:body>

<h3>JSF CustomValidators Example</h3>
 
Name :  
<h:outputText value="#{user.name}">
</h:outputText>
<br />
Place :  
<h:outputText value="#{user.place}">
</h:outputText>
<br />
Age :  
<h:outputText value="#{user.age}">
</h:outputText>
<br />
Salary :  
<h:outputText value="#{user.salary}">
</h:outputText>
<br />
Password :  
<h:outputText value="#{user.password}">
</h:outputText>
<br />
Email :  
<h:outputText value="#{user.email}">
</h:outputText>
 

</h:body>
</html>

Other then Annotation we can configure custom validator in faces-config.xml

<validator>
<description>
Validates that the current user has met the requirements for the event.
</description>
<validator-id>emailValidator</validator-id>
<validator-class>
com.javasafari.EmailValidator
</validator-class>
</validator>

Run Application:


jsf-custom-validator

Enter valid email and submit

jsf-custom-validator