I am using Spring MVC 2.5 and for my model/bean class, at the moment, I use server side validation. One of the validation I wanted to do is check if some of the inputs are not numeric (0-9). The user may input non-numeric characters like "abcd" instead of '1234'.
I have a @Pattern which only accepts positive BigDecimal (it represents dollar amount).
public class OfferSettingBean implements Serializable {
private static final String NUMBER_WITH_DECIMAL_PLACES_ONLY="^\\d+([.]\\d+)?$";
//org.hibernate.validator.pattern
@Pattern(regex = NUMBER_WITH_DECIMAL_PLACES_ONLY, message = "invalid.amount")
private BigDecimal offerSize;
//the rest of the code goes here including setter and getter methods
}
jsp page
<input type="text" name="offerSize" id="offerSize" value="${offerSetting.offerSize}" placeholder="$" />
The problem with my code is, if the user enters a non number character like "asdfsd" it doesnt even reach to the point where it should check the pattern.
Failed to convert property value of type [java.lang.String] to required type [java.math.BigDecimal] for property offerSize; nested exception is java.lang.NumberFormatException
I think the problem is before checking the pattern it binds the string value to BigDecimal which makes it fail.
One ugly solution might be in the offerSize setter method I can check the coming value and do something if it is not a number. But I dont like that one.
What is a better way to deal with such kind of binding problems?
FYI: I know I am going to do client side validation (using JQuery) latter on. Now, I assume the user by passes the client side validation in some way.