2011-05-01 57 views
0

我想验证一个字段能够接受值只有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); 
      } 
     } 
    } 

这是错误我消息我看到当我酯的东西,不是数字:

enter image description here

为什么我没有看到消息:Only numbers allo星期三?

+1

我不确定,但不是这个字段productValue而不是discountPercentage? – MByD 2011-05-01 12:05:59

+0

是的,你是对的另一个领域叫productValue具有相同的问题,我只是打印屏蔽了错误的一个。 – sfrj 2011-05-01 17:33:33

回答

0

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

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

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

此外,您的错误消息是为productValue而不是为discountPercentage