Skip to main content

JSF Tip #36 - Create a custom validator

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

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 {

    @Override
    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")
@RequestScoped
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) {
        this.name = name;
    }
}

And the JSF page.

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Custom Validator - f:validator tag</title>
    </h:head>
    <h:body>
        <h2>Custom Validator - f:validator tag</h2>
        <h:form>
            <h:inputText value="#{customValidatorBean.custom.name}">
                <f:validator validatorId="customValidatorId"/>
            </h:inputText>
            <h:commandButton value="Submit"/>
        </h:form>
    </h:body>
</html>

Note the code for this sample is available as part of the Glassfish samples (see the subversion repository at http://svn.java.net/svn/glassfish-samples~svn/trunk/ws/javaee7)

And that is it.

Enjoy!

Related Topics >>