Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

jsf 2 - JSF greater than zero validator

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...