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;

@FacesValidator("com.vinod.jsf.MyValidator")
public class MyValidator implements Validator {

    @Override
    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.");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }
    }

}

2. Create Managed Bean

package com.vinod.jsf;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class ValidatorBean {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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>JSF Validator</title>
</h:head>
<h:body>
    <h2>JSF Validator Example</h2>
    <h:form id="vinod">
        <h:outputText id="name" value="Name :" />
        <h:inputText id="nametext" value="#{validatorBean.name}">
            <f:validator validatorId="com.vinod.jsf.MyValidator" />
        </h:inputText>
        <h:message for="nametext" style="color:red;margin:8px;" ></h:message>
        <h:commandButton value="Validate" id="submit"
            action="#{validatorBean.validatorAction}">
        </h:commandButton>
    </h:form>
</h:body>
</html>


4. Output



Download example

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts