Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 891
jack Avatar asked Dec 10 '22 12:12

jack


2 Answers

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);
    }
like image 170
Niall Thomson Avatar answered Dec 28 '22 14:12

Niall Thomson


In order to use @DateTimeFormat you need to install FormattingConversionServiceFactoryBean. <mvc:annotation-driven> does it implicitly, but if you cannot use it you need something like this:

<bean id="conversionService" 
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /> 

<bean id="annotationMethodHandlerAdapter"    
    class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="webBindingInitializer">
        <bean id="configurableWebBindingInitializer"
            class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> 
            <property name="validator"><ref bean="validator"/>
            <proeprty name = "conversionService" ref = "conversionService" />
        </bean>
    </property>
</bean>
like image 28
axtavt Avatar answered Dec 28 '22 13:12

axtavt