August 6 2015

Jsf custom validator

Jsf custom validator

A custom validator in Jsf can be created by implementing javax.faces.validator.Validator interface which has a one method (validate).

public void validate(FacesContext context, UIComponent component,Object value) throws ValidatorException;

The class has to implement validate method. If component’s value is not according to the expected, throw a new ValidatorException instance. If an exception is thrown, Jsf will automatically add the FacesMessage instance to the message queue.

The validator has to be registered and a unique identifier has to be assigned to it. Validator can be registered by adding it in faces-config.xml or by adding @FacesValidator annotation to the Validator class.

The validator can be applied to the component using <f:validator> by passing the validator unique identifier as parameter.


<f:validator validator=”uniqueidentifer”/>




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns=""
xmlns:h=""> <h:head>
<title>Jsf custom validator</title>



<h2> Jsf custom validator </h2>
<h:messages />

<h:panelGrid columns="2">

<h:outputText value="User Name" />
<h:inputText value="#{userManagedBean.userName}" />
<h:outputText value="Password" />
<h:inputText value="#{userManagedBean.password}">
<f:validator validatorId="com.answersz.passwordValidator" />

<h:commandButton value="Save" action="#{userManagedBean.saveUser}" />




package com.answersz;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name = "userManagedBean")
public class UserManagedBean {

private String userName;
private String password;

public void saveUser() {

public String getUserName() {
return userName;

public void setUserName(String userName) {
this.userName = userName;

public String getPassword() {
return password;

public void setPassword(String password) {
this.password = password;


package com.answersz;

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;

public class PasswordValidator implements Validator {

public void validate(FacesContext arg0, UIComponent component,
Object companentValue) throws ValidatorException {

String password = companentValue.toString();

if (password.contains("@") || password.contains("$") || password.contains("%")) {

FacesMessage facesMessage = new FacesMessage("Invalid Password");

throw new ValidatorException(facesMessage);



jsf custom validator

Copyright © 2014. All rights reserved.

Posted August 6, 2015 by answersz in category Jsf

Leave a Comment

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