验证 int 值

发布于 2024-11-04 08:18:57 字数 1720 浏览 0 评论 0 原文

我在对具有值(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

I am having difficulties doing a simple validation of a text field that has as a value - an int variable.

I need the following;

  • permit only digits
  • don't allow a value of 0 or bellow
  • It has to be mandatory to fill the field according to the rules above.

This is the validator I created, but it does not work as I desire. Can you have a look at it and tell me where I am making the mistake?

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);
        }       
    }

This is how I call the field:

<h:inputText id="productValue" value="#{newOfferSupportController.productValue}" validator="#{newOfferSupportController.validateProductValue}"/>

This the validation shown in the browser:
enter image description here

Text

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你是年少的欢喜 2024-11-11 08:18:57

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

You should be able to enforce the conditions your looking just using a regular expression:
^[1-9]+[0-9]*$

初见 2024-11-11 08:18:57

首先你的正则表达式是错误的。您需要将 $ 放在末尾,例如 ^([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,您也可以输入负数值,例如长度为 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:

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

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 so value might be an Integer and not a String.

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:

  • first a converter is called in order to convert the string to an integer and the other way round, especially if your model field is an Integer - this is where you'd check if you actually got an integer
  • second you validate the integer value, e.g. by enforcing a minimum - here you're using a validator

Also note that there are already built in validators, that do what you want. Take a look at <f:validateLongRange minimum = "0"/> for example.

も星光 2024-11-11 08:18:57

首先, value 实际上是 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");
}

First, is value actually an instance of String? Or can it be cast to an Integer?

If not, do this:

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");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文