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.
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?
<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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.