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/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…