验证 int 值
我在对具有值(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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该能够仅使用正则表达式来强制执行您所查看的条件:
^[1-9]+[0-9]*$
You should be able to enforce the conditions your looking just using a regular expression:
^[1-9]+[0-9]*$
首先你的正则表达式是错误的。您需要将
$
放在末尾,例如^([0-9]+)?$
。这并不像您期望的那样工作:
inputFormField.length()
是文本的长度,它不能小于 0,即使它大于 0,您也可以输入负数值,例如长度为 2 的"-1"
。如果我正确地看到异常,您将收到 ClassCastException。看一下第 44 行(异常消息告诉您),我猜它是
String inputFromField = (String) value;
您是否为该字段定义了转换器?如果是这样,value
可能是一个Integer
而不是String
。编辑:
请注意,您的验证器实际上尝试做两件事:将输入转换为整数并验证整数值。在 JSF 中,您通常有两个类来执行此操作:
另请注意,已经内置了验证器,可以执行您想要的操作。例如,看一下
。First of all your regex is wrong. You need to put
$
at the end, like this^([0-9]+)?$
.This doesn't work as you might expect:
inputFormField.length()
is the length of the text, which can't be less than 0 and even if it were greater than 0 you could enter a negative value, e.g."-1"
which has length 2.If I see the exception correctly, you're getting a ClassCastException. Take a look at line 44 (which you are told by the exception message), which I guess is
String inputFromField = (String) value;
Did you define a converter for that field? If sovalue
might be anInteger
and not aString
.Edit:
Note that your validator actually tries to do two things: convert the input to an integer and validate the integer value. In JSF you normally have two classes that do this:
Also note that there are already built in validators, that do what you want. Take a look at
<f:validateLongRange minimum = "0"/>
for example.首先, value 实际上是 String 的实例吗?或者可以将其转换为整数吗?
如果没有,请执行以下操作:
First, is value actually an instance of String? Or can it be cast to an Integer?
If not, do this: