Spring MVC Validation BindingResult

Posted on September 7, 2011
Tags: java, Spring

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”:

public String saveObject(ModelMap model,
            @Valid @ModelAttribute ObjectClass myObject, BindingResult result)

This did work:

public String saveObject(ModelMap model,
            @Valid @ModelAttribute("myObject") ObjectClass myObject, BindingResult result)

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

<form:form commandName="myObject">
...
<form:errors path="attr" />
...
</form:form>