Skip to main content

JSF Tip #36 - Create a custom validator

Posted by mriem on November 11, 2013 at 3:32 PM PST

Note this blog is obsolete, see for the current blog

How can you create a custom validator and use it? See below!

Creating the custom validator class

package customvalidator;

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(value = "customValidatorId")
public class CustomValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String name = (String) value;
        if (name != null && !name.equals("Duke")) {
            throw new ValidatorException(new FacesMessage("Your name is not Duke!"));

A sample managed bean using the custom validator.

package customvalidator;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean(name = "customValidatorBean")
public class CustomValidatorBean {

    private Custom custom = new Custom();

    public Custom getCustom() {
        return custom;

    public void setCustom(Custom custom) {
        this.custom = custom;

The model object of the example.

package customvalidator;

public class Custom {

    private String name;

    public String getName() {
        return name;

    public void setName(String name) { = name;

And the JSF page.

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE html>

<html xmlns=""
        <title>Custom Validator - f:validator tag</title>
        <h2>Custom Validator - f:validator tag</h2>
            <h:inputText value="#{}">
                <f:validator validatorId="customValidatorId"/>
            <h:commandButton value="Submit"/>

Note the code for this sample is available as part of the Glassfish samples (see the subversion repository at

And that is it.


Related Topics >>