JSF大于零的验证器 [英] JSF greater than zero validator
问题描述
如何在JSF中创建一个验证器,以验证输入文本是否大于零?
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>
我有上面的代码,但是我不确定这是否最佳.尽管它可以工作,但是如果需要比这个数字小的另一个数字,那么我需要再次更改jsf文件. 用例是,任何大于零的值都可以,但不能为负数.
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.
有什么想法吗?
推荐答案
只需创建一个自定义验证器,即实现进行注释.
Just create a custom validator, i.e. a class implementing javax.faces.validator.Validator
, and annotate it with @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页面中使用它:
And use it in the facelets page like this:
<h:inputText id="percentage" value="#{lab.percentage}">
<f:validator validatorId="positiveNumberValidator" />
</h:inputText>
有用的链接: http://www.mkyong.com/jsf2/custom -validator-in-jsf-2-0/
这篇关于JSF大于零的验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!