只需创建一个自定义验证器,即一个实现 . 的类javax.faces.validator.Validator
,并用@FacesValidator("positiveNumberValidator")
.
像这样实现validate()
方法:
@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);
}
}
并在 facelets 页面中使用它,如下所示:
<h:inputText id="percentage" value="#{lab.percentage}">
<f:validator validatorId="positiveNumberValidator" />
</h:inputText>
有用的链接:http ://www.mkyong.com/jsf2/custom-validator-in-jsf-2-0/