2011-05-01 56 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