自定义验证错误无法按预期工作

问题描述

| 我想验证一个字段,使其只能接受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);
            }
        }
    }
这是我收到不是数字的东西时看到的错误消息: 为什么我看不到消息:只允许输入数字?     

解决方法

您为什么不为此目的使用jsf的
LongRangeValidator
<h:inputText id=\"discountPercentage\" 
      value=\"#{newOfferSupportController.discountPercentage}\">
   <f:validateLongRange minimum=\"1\" maximum=\"100\"/>
</h:inputText>
如果默认消息不符合您的需求,您甚至可以定义自己的自定义验证消息。有关更多信息,请参见此答案。 除此之外,您的错误消息是针对
productValue
而不是针对
discountPercentage
。     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...