Custom Validator in JSF

Custom Validator in JSF

This tips presents sample programs for how to write the custom validator in JSF application. There is many built-in validators available in JSF.

also read:

You can learn about the predefined tags in the article Introduction to JSF Core Tags Library . If you are new to JSF please read this article Introduction to Java Server Faces. The sample programs includes how to validate a numeric field. Here you have to focus on how the validation class is implemented and in which phase the methods are called. For your understanding we also included the PhaseListener implementation.

JSP File (index.jsp)

 
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<html>
    <body>
        <f:view>
            <h:form>
                <h:messages/>
                <h:inputText value="#{jsfBean.field}">
                    <f:validator validatorId="customValidator"/>
                </h:inputText>
                <h:commandButton action="#{jsfBean.submit}" value="Submit">
                    <f:phaseListener binding="#{jsfBean.phaseListenerImpl}"
                          type="javabeat.jsf.PhaseListenerImpl"/>
                </h:commandButton>
            </h:form>
        </f:view>
    </body>
</html>

JavaBean (JavaBeatJsfBean.java)

 
package javabeat.jsf;

/**
 * source : www.javabeat.net
 */
public class JavaBeatJsfBean {

    private String field;
    private PhaseListenerImpl phaseListenerImpl;

    public PhaseListenerImpl getPhaseListenerImpl() {
        return phaseListenerImpl;
    }

    public void setPhaseListenerImpl(PhaseListenerImpl phaseListenerImpl) {
        this.phaseListenerImpl = phaseListenerImpl;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public String submit() {
        System.out.println(this.field);
        return "success";
    }
}

CustomValidator.java

 package javabeat.jsf;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * source : www.javabeat.net
 */
public class CustomValidator implements Validator {

    public void validate(FacesContext facesContext, UIComponent arg1, Object value) throws ValidatorException {
        String inputValue = (String) value;
        int length = inputValue.length();
        for (int i = 0; i &lt; length; i++) {
            Character character = inputValue.charAt(i);
            boolean isValid = Character.isDigit(character);
            if (!isValid) {
                FacesMessage facesMessage = new FacesMessage("Invalid Input", "message");
                FacesContext.getCurrentInstance().addMessage("message", facesMessage);
                break;
            }
        }
    }
}

PhaseListenerImpl.java

 package javabeat.jsf;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
/**
 * source : www.javabeat.net
 */
public class PhaseListenerImpl implements PhaseListener{
    public void afterPhase(PhaseEvent event) {
        System.out.println("After Executing " + event.getPhaseId());
    }
    public void beforePhase(PhaseEvent event) {
        System.out.println("Before Executing " + event.getPhaseId());
    }
    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    }
}

faces-config.xml

 
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="1.2"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

    <managed-bean>
        <managed-bean-name>jsfBean</managed-bean-name>
        <managed-bean-class>javabeat.jsf.JavaBeatJsfBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <validator>
        <validator-id>customValidator</validator-id>
        <validator-class>javabeat.jsf.CustomValidator</validator-class>
    </validator>
</faces-config>

Output in the command prompt

 
Before Executing RENDER_RESPONSE 6
After Executing RENDER_RESPONSE 6
Before Executing APPLY_REQUEST_VALUES 2
After Executing APPLY_REQUEST_VALUES 2
Before Executing PROCESS_VALIDATIONS 3
After Executing PROCESS_VALIDATIONS 3
Before Executing UPDATE_MODEL_VALUES 4
After Executing UPDATE_MODEL_VALUES 4
Before Executing INVOKE_APPLICATION 5
1232
After Executing INVOKE_APPLICATION 5
Before Executing RENDER_RESPONSE 6
After Executing RENDER_RESPONSE 6

Javabeat has published many of the good articles related to Java Server Faces (JSF). This list will help you to learn the basic concepts on JSF and how to start using in your projects, please have a look on these articles when time permits. Don’t forget to leave your feedback on the comments section. This helps us to provide better content for you.

The above article would provide the higher level of understanding on each concept. If you would like to know all the features in detail, please read any of the JSF books listed in the book recommendations for Java Server Faces (JSF). Hope this helps you!!

If you would like to receive future mails on Java articles, please subscribe here.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better