Thursday, July 7, 2016

Custom Validator For Long



Custom Long Validator

JSF makes it very easy to create a custom validator class and tag. Your custom validator class must implement the javax.faces.validator.Validator interface which will require a validate method. Next you will need to register your validator in faces-config.

package com.hello.webapp;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import com.hello.webapp.util.MessageUtil;

public class MyLongRangeValidator implements Validator, StateHolder {
    
    public static final String VALIDATOR_ID    = "MyLongRangeValidator";
    public static final String NOT_IN_RANGE_MESSAGE_ID = "NotInRangeID";
    public static final String MINIMUM_MESSAGE_ID = "MinId";
    public static final String MAXIMUM_MESSAGE_ID = "MaxId";
    public static final String TYPE_MESSAGE_ID = "javax.faces.validator.LongRangeValidator.TYPE_detail";
    private Long minimum = null;
    private Long maximum = null;

    // CONSTRUCTORS
    public LongRangeValidator() {
    }

    /**
    *
    * @param facesContext
    * @param uiComponent
    * @param value
    */
    public void validate(FacesContext facesContext,
    UIComponent uiComponent,
    Object value)
    throws ValidatorException {
        if (facesContext == null) throw new NullPointerException("facesContext");
        if (uiComponent == null) throw new NullPointerException("uiComponent");
        if (value == null){
            return;
        }
        //set maximum and minimum values
        if(uiComponent.getAttributes().get("minimum") != null) {
            setMinimum(Long.valueOf((String)uiComponent.getAttributes().get("minimum")));
        }
        if(uiComponent.getAttributes().get("maximum") != null) {
            setMaximum(Long.valueOf((String)uiComponent.getAttributes().get("maximum")));
        }
        long lvalue = parseLongValue(facesContext, uiComponent,value);
        if (minimum != null && maximum != null) {
            if (lvalue < minimum.longValue() || lvalue > maximum.longValue()) {
                List list = new ArrayList();
                list.add(uiComponent.getClientId());
                list.add(minimum);
                list.add(maximum);
                throw new ValidatorException(new FacesMessage(MessageUtil.getMessage(NOT_IN_RANGE_MESSAGE_ID,list,facesContext)));
            }
        } else if (minimum != null) {
            if (lvalue < minimum.longValue()) {
                List list = new ArrayList();
                list.add(uiComponent.getClientId());
                list.add(minimum);
                list.add(maximum);
                throw new ValidatorException(new FacesMessage(MessageUtil.getMessage(MINIMUM_MESSAGE_ID,list,facesContext)));
            }
        } else if (maximum != null) {
            if (lvalue > maximum.longValue()) {
                List list = new ArrayList();
                list.add(uiComponent.getClientId());
                list.add(minimum);
                list.add(maximum);
                throw new ValidatorException(new FacesMessage(MessageUtil.getMessage(MAXIMUM_MESSAGE_ID,list,facesContext)));
            }
        }
    }
    private long parseLongValue(FacesContext facesContext, UIComponent uiComponent, Object value)
    throws ValidatorException {
        if (value instanceof Number) {
            return ((Number)value).longValue();
        } else {
            try {
                return Long.parseLong(value.toString());
            }
            catch (NumberFormatException e) {
                List list = new ArrayList();
                list.add(uiComponent.getClientId());
                list.add(minimum);
                list.add(maximum);
                throw new ValidatorException(new FacesMessage(MessageUtil.getMessage(TYPE_MESSAGE_ID,list,facesContext)));
            }
        }
    }
    // GETTER & SETTER
    public long getMaximum() {
        return maximum != null ? maximum.longValue() : Long.MAX_VALUE;
    }
    public void setMaximum(long maximum){
        maximum = new Long(maximum);
    }
    public long getMinimum() {
        return minimum != null ? minimum.longValue() : Long.MIN_VALUE;
    }
    public void setMinimum(long minimum) {
        minimum = new Long(minimum);
    }
}
 

faces-config.xml:


<validator>
 <validator-id>myLongRangeValidator</validator-id>
 <validator-class>com.hello.webapp.MyLongRangeValidator</validator-class>
</validator>

Page Usage:

<h:inputText id="year" size="2" required="true" maxlength="2" value="Year" styleClass="validatecomp alignR imeDisabled" readonly="#{myForm.allReadonly and myForm.notReadonly}">
 <!-- validateLongRange start -->
 <f:validator validatorId="insCoreLongRangeValidator" />
 <f:attribute name="minimum" value="1" />
 <f:attribute name="maximum" value="99" />
 <f:attribute name="labelId" value="yearLabel"/>
 <!-- validateLongRange end -->
</h:inputText>

Requiring a Value


If a UIInput component does not have the required attribute set to  true  and the user does not enter a value, then the validator will not be called. Remember to set  required="true" , if you want to force validation.

 

6 comments: