Tuesday, 16 April 2013

JSF Custom Validator simple example

Here is one simple example to create custom Validator in JSF. In this example name field is validating like whether the names starts with Mr or not.

1. Create a Validator class

package com.vinod.jsf;

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 MyValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String name = (String) value;
        if (!name.startsWith("Mr.")) {
            FacesMessage message = new FacesMessage();
            message.setDetail("Name should start with Mr.");
            message.setSummary("Name should start with Mr.");
            throw new ValidatorException(message);


2. Create Managed Bean

package com.vinod.jsf;

import javax.faces.bean.ManagedBean;

public class ValidatorBean {
    private String name;

    public String getName() {
        return name;

    public void setName(String name) { = "Hello  " + name;

    public ValidatorBean() {

    public String validatorAction() {
        System.out.println("Validator bean action");
        return "ValidatorExample.xhtml";

3. Create a Facelet page

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns=""
    <title>JSF Validator</title>
    <h2>JSF Validator Example</h2>
    <h:form id="vinod">
        <h:outputText id="name" value="Name :" />
        <h:inputText id="nametext" value="#{}">
            <f:validator validatorId="com.vinod.jsf.MyValidator" />
        <h:message for="nametext" style="color:red;margin:8px;" ></h:message>
        <h:commandButton value="Validate" id="submit"

4. Output

Download example