【发布时间】:2011-08-16 09:57:47
【问题描述】:
我想验证一个字段,使其只能接受 1 到 100 之间的值。它工作正常,但是当我写一个不是整数的东西时,看不到我期望的自定义消息。
这是字段:
<h:inputText id="discountPercentage" value="#{newOfferSupportController.discountPercentage}" validator="#{newOfferSupportController.validateDiscountPercentage}"/>
<span style="color: red;"><h:message for="discountPercentage"
showDetail="true" /></span>
这是验证器方法:
public void validateDiscountPercentage(FacesContext context,
UIComponent validate, Object value) {
FacesMessage msg = new FacesMessage("");
String inputFromField = "" + value.toString();
String simpleTextPatternText = "^([1-9]|[1-9]\\d|100)$";
Pattern textPattern = null;
Matcher productValueMatcher = null;
textPattern = Pattern.compile(simpleTextPatternText);
productValueMatcher = textPattern.matcher(inputFromField);
if (!productValueMatcher.matches()) {
msg = new FacesMessage("Only values between 1 and 100 allowed");
throw new ValidatorException(msg);
}
for (int i = 0; i < inputFromField.length(); i++) {
// If we find a non-digit character throw Exception
if (!Character.isDigit(inputFromField.charAt(i))) {
msg = new FacesMessage("Only numbers allowed");
throw new ValidatorException(msg);
}
}
}
这是我在酯化不是数字的东西时看到的错误消息:
为什么我看不到消息:只允许数字?
【问题讨论】:
-
我不确定,但是这个字段不是 productValue 而不是 discountPercentage 吗?
-
是的,你是对的,还有另一个名为 productValue 的字段存在同样的问题,我只是打印筛选了错误的字段。
标签: java validation jsf jsf-2