繁体   English   中英

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

[英]Custom validation error don't work as expected

我想验证一个字段是否只能接受 1 到 100 之间的值。它工作正常,但是当我写一个不是 integer 的东西时,看不到我期望的自定义消息。

这是字段:

<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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM