简体   繁体   English

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

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

I want to validate a field to be able to accept values only between 1 and 100. It works fine, but when i write a something that is not an integer is don't see the custom message i expect.我想验证一个字段是否只能接受 1 到 100 之间的值。它工作正常,但是当我写一个不是 integer 的东西时,看不到我期望的自定义消息。

This is the field:这是字段:

<h:inputText id="discountPercentage" value="#{newOfferSupportController.discountPercentage}" validator="#{newOfferSupportController.validateDiscountPercentage}"/>
            <span style="color: red;"><h:message for="discountPercentage"
                showDetail="true" /></span>

This is the validator method:这是验证器方法:

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

This is the error i message i see when i ester something that is not a number:这是我在酯化不是数字的东西时看到的错误消息:

在此处输入图像描述

Why i don't see the message: Only numbers allowed?为什么我看不到消息:只允许数字?

Why don't you use jsf's LongRangeValidator for this purpose?你为什么不为此目的使用 jsf 的LongRangeValidator呢?

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

You can even define your own custom validation messages if the default messages don't fit your needs.如果默认消息不符合您的需要,您甚至可以定义自己的自定义验证消息。 See this answer for more information.有关更多信息,请参阅此答案

Besides this, your error message is for productValue and not for discountPercentage .除此之外,您的错误消息是针对productValue而不是针对discountPercentage

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

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