【问题标题】:Custom validation error don't work as expected自定义验证错误未按预期工作
【发布时间】:2011-08-16 09:57:47
【问题描述】:

我想验证一个字段,使其只能接受 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);
            }
        }
    }

这是我在酯化不是数字的东西时看到的错误消息:

为什么我看不到消息:只允许数字?

【问题讨论】:

  • 我不确定,但是这个字段不是 productValue 而不是 discountPercentage 吗?
  • 是的,你是对的,还有另一个名为 productValue 的字段存在同样的问题,我只是打印筛选了错误的字段。

标签: java validation jsf jsf-2


【解决方案1】:

你为什么不使用 jsf 的LongRangeValidator 来达到这个目的?

<h:inputText id="discountPercentage" 
      value="#{newOfferSupportController.discountPercentage}">
   <f:validateLongRange minimum="1" maximum="100"/>
</h:inputText>

如果默认消息不符合您的需求,您甚至可以定义自己的自定义验证消息。请参阅this answer 了解更多信息。

除此之外,您的错误消息是针对productValue 而不是针对discountPercentage

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 1970-01-01
    • 2010-10-11
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多