Spring MVC Validation BindingResult

Posted on September 7, 2011

A quick note about using the BindingResult to detect and report errors in a form. One gotcha that got me was the need to set a name on the @ModelAttribute in order to properly relate the form:form commandName and the validation object. Essentially, if you don’t set a name then @ModelAttribute will get the command name from the name of the argument, and BindingResult will get the command name from the type of the argument, meaning that when you go to use form:errors nothing will be displayed.

ie, this didn’t work because @ModelAttribute was using “myObject”, while BindingResult was using “objectClass”:

This did work:

At the JSP end things looked like this, where “attr” is an attribute that is being checked: