I spent the entire morning trying to figure out how to get Spring MVC to allow for Null in my Date field. I would get an exception if the Date value in the form was left Null. Once I found that out, I wasn’t getting any validation messages for all the fields marked as @NotNull. It turns out Spring just set the value to empty string instead of null if the field was empty. Hibernate’s JSR-303 implementation has a @NotEmpty validation, but I decided to try to keep it to spec.
So, I implemented a custom @InitBinder for my @Controller and had an anonymous implementation of a custom editor all based off an answer on stackoverflow.com. Finally, I found this bug logged against Roo
https://jira.springsource.org/browse/ROO-190
Using that single line in my @InitBinder method I was then able to set Dates to null. For the second problem, I used this very helpful blog post by Stefan Reuter
http://blogs.reucon.com/srt/2007/11/25/spring_mvc_null_or_an_empty_string.html
So, now my @InitBinder method looks like this.
@InitBinder
public void allowEmptyDateBinding( WebDataBinder binder )
{
// Allow for null values in date fields.
binder.registerCustomEditor( Date.class, new CustomDateEditor( new SimpleDateFormat( getDatePattern()), true ));
// tell spring to set empty values as null instead of empty string.
binder.registerCustomEditor( String.class, new StringTrimmerEditor( true ));
}
And as simple as that I get null instead of empty string for my string values, and I can allow null values in my non-required date fields. Too bad it took me 6 hours this morning to find the answers.
great fix and worked for me. I also spent countless hours trying to find a way to allow null on a JSR-303 validated field – thank you!!!
Comment by Dan — 2011/03/07 @ 5:03 pm
Glad it helped. It took me hours to find it too, so I was hoping I would make it easier for someone else.
Comment by digitaljoel — 2011/03/07 @ 9:10 pm
thank you
Comment by jasmin — 2013/05/02 @ 1:49 pm