JSF greater than zero validator

浪子不回头ぞ 提交于 2019-12-18 05:57:29

问题


How do you create a validator in JSF that validates the input text if it is greater than zero?

<h:inputText id="percentage" value="#{lab.percentage}">
    <f:validateDoubleRange minimum="0.000000001"/>
</h:inputText>

I have the code above but I am not sure if this is optimal. Although it works but if another number lesser than this is needed then I need to change the jsf file again. The use case is that anything that is greater than zero is okay but not negative number.

Any thoughts?


回答1:


Just create a custom validator, i.e. a class implementing javax.faces.validator.Validator, and annotate it with @FacesValidator("positiveNumberValidator").

Implement the validate() method like this:

@Override
public void validate(FacesContext context, UIComponent component,
        Object value) throws ValidatorException {

    try {
        if (new BigDecimal(value.toString()).signum() < 1) {
            FacesMessage msg = new FacesMessage("Validation failed.", 
                    "Number must be strictly positive");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg); 
        } 
    } catch (NumberFormatException ex) {
        FacesMessage msg = new FacesMessage("Validation failed.", "Not a number");
        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
        throw new ValidatorException(msg); 
    }
}

And use it in the facelets page like this:

<h:inputText id="percentage" value="#{lab.percentage}">
    <f:validator validatorId="positiveNumberValidator" />
</h:inputText>

Useful link: http://www.mkyong.com/jsf2/custom-validator-in-jsf-2-0/



来源:https://stackoverflow.com/questions/18071219/jsf-greater-than-zero-validator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!