I've begun learning to use Spring MVC's validation annotations. So far, everything has been going well, but now I've come across an issue which has halted me in my tracks. An exception is being thrown when the string returned from a webpage field is being parsed into a Long, but the string contains non numeric characters. Whilst expected behaviour, presenting a user friendly error message is proving to be a challenge.
What I have so far:
in webpage.jsp, the Spring error is being displayed by:
<form:errors path="numberField" cssclass="error"></form:errors>
In the controller for the webpage, we have:
@RequestMapping(method = RequestMethod.POST)
public String post(Model model, @Valid @ModelAttribute Item item, BindingResult bindingResult) {
//Stuff
return "redirect:" + ITEM_PAGE;
}
Item class has validation annotations on the members and they all work as expected.
The error message return from the bindingResult on the jsp next to the appropriate field is:
Failed to convert property value of type java.lang.String to required type java.lang.Long for property quantity; nested exception is java.lang.NumberFormatException: For input string: "n0t"
As I've said above, this is not unexpected, but I would like to replace that message with something like
Please input a number
I'd like to keep it to minimal amounts of extra code, but if the only way is to create my own validator, I might go down that route. Are there any other ways to handle the exception and return a nicer error message?
Thanks!
Sorry that this is not runnable code, but I cant post any more.