【发布时间】:2011-08-16 09:25:50
【问题描述】:
我在对具有值的文本字段进行简单验证时遇到了困难 - 一个 int 变量。
我需要以下;
- 只允许数字
- 不允许使用 0 或以下的值
- 必须按照上述规则填写该字段。
这是我创建的验证器,但它没有按我的意愿工作。你能看看它并告诉我我哪里出错了吗?
public void validateProductValue(FacesContext context,
UIComponent validate, Object value) {
FacesMessage msg = new FacesMessage("");
String inputFromField = (String) value;
String simpleTextPatternText = "^([0-9]+$)?";
Pattern textPattern = null;
Matcher productValueMatcher = null;
textPattern = Pattern.compile(simpleTextPatternText);
productValueMatcher = textPattern.matcher(inputFromField);
if (!productValueMatcher.matches()) {
msg = new FacesMessage("Only digits allowed");
throw new ValidatorException(msg);
}
if (inputFromField.length() <= 0) {
msg = new FacesMessage("You must enter a value greater than 0");
throw new ValidatorException(msg);
}
if (Integer.parseInt(inputFromField.toString().trim()) <= 0) {
msg = new FacesMessage("0 or bellow is not permited");
throw new ValidatorException(msg);
}
}
这就是我对这个领域的称呼:
<h:inputText id="productValue" value="#{newOfferSupportController.productValue}" validator="#{newOfferSupportController.validateProductValue}"/>
这是在浏览器中显示的验证:
文字
/newoffer.xhtml @44,184
validator="#{newOfferSupportController.validateProductValue}":
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
【问题讨论】:
-
验证信息难以阅读,能否复制文字或放大图片?
-
您发布的错误表明您正在传递一个 Integer 对象,并且尝试将其转换为字符串失败。
标签: java validation jsf jsf-2