验证int值

时间:2011-05-01 09:06:48

标签: java validation jsf jsf-2

我很难对作为值的文本字段进行简单验证 - 一个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}"/>

这是浏览器中显示的验证: enter image description here

文本

/newoffer.xhtml @44,184 
validator="#{newOfferSupportController.validateProductValue}":
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

3 个答案:

答案 0 :(得分:1)

首先你的正则表达式是错误的。您需要将$放在最后,例如^([0-9]+)?$

这不会像您预期的那样有效:

if (inputFromField.length() <= 0) {
  msg = new FacesMessage("You must enter a value greater than 0");
  throw new ValidatorException(msg);
}

inputFormField.length()是文本的长度,不能小于0,即使大于0,也可以输入负值,例如"-1"长度为2。

如果我正确看到异常,那么您将获得ClassCastException。看看第44行(异常消息告诉你),我猜是String inputFromField = (String) value;您是否为该字段定义了转换器?如果是,value可能是Integer而不是String

编辑:

请注意,您的验证器实际上尝试做两件事:将输入转换为整数并验证整数值。在JSF中,您通常有两个类来执行此操作:

  • 首先调用一个转换器,以便将字符串转换为整数,反之亦然,特别是如果你的模型字段是一个整数 - 这是你检查你是否真的有一个整数的地方
  • 秒验证整数值,例如通过强制执行最低限度 - 这里您使用验证器

另请注意,已经内置验证器,可以执行您想要的操作。例如,查看<f:validateLongRange minimum = "0"/>

答案 1 :(得分:1)

您应该能够使用正则表达式强制执行您所查看的条件:     ^ [1-9] + [0-9] * $

答案 2 :(得分:0)

首先,值实际上是String的一个实例吗?或者可以将其转换为整数?

如果没有,请执行以下操作:

if (value == null) {
   throw new ValidatorException("No input value");
}

String inputValue = (String) value;

try {
   int v = Integer.parse(inputValue);

   if (v <= 0) {
      throw new ValidatorException("Input less than or equal to 0");
   }     


} catch (NumberFormatException e) {
   throw new ValidatorException("Input is not an integer");
}