Search code examples
springhibernate-validator

Spring validation: can't convert from String to Date


I'm doing some spring form validation, however I'm getting:

Failed to convert property value of type 'java.lang.String' to required type 'ja
va.util.Date' for property 'birthdate'; nested exception is java.lang.Illega
lStateException: Cannot convert value of type [java.lang.String] to required typ
e [java.util.Date] for property 'birthdate': no matching editors or conversi
on strategy found

However, in my modelAttribute form I have:

@NotNull
 @Past
 @DateTimeFormat(style="S-")
 private Date birthdate;

I thought the DateTimeFormat was responsible for this?

I'm using the hibernate-validator 4.0.


Solution

  • Theres a chance you'll have to use register a CustomDateEditor in your controller(s) to convert from a String to a Date. The example method below goes in your controller, but you'll have to change the date format to match whatever you're using.

    
    @InitBinder
        public void initBinder(WebDataBinder binder) {
            CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true);
            binder.registerCustomEditor(Date.class, editor);
        }