August 7 2015

Jsf validator method

Jsf validator method

Jsf validation can be done in three ways using standard validation tags, validator methods in backing beans and validator classes. Validator method and validator classes are used to write application specific or custom validations.

Validator methods are created when the validation is specific to the page. The validator methods are created in the backing beans and it should have the following syntax

public void methodname(FacesContext facesContext,UIComponent component,

Object objectToValidate) throws ValidatorException

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 attribute is used to associate validator method with UI component

<h:inputText value=”#{value-binding}” validator=”#{ method-binding}” />



<?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 validator method</title>



<h2> Jsf validator method </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}"
validator="#{userManagedBean.validatePassword}" />

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



package com.answersz;

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

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

private String userName;
private String password;

public void saveUser() {

public void validatePassword(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);


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;


jsf validator method

Copyright © 2014. All rights reserved.

Posted August 7, 2015 by answersz in category Jsf

Leave a Comment

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