Spring MVC form validation Date field

后端 未结 2 1844
自闭症患者
自闭症患者 2021-01-12 11:18

I have a form field that should be converted to a Date object, as follows:


And I have requirement to mak

2条回答
  •  孤街浪徒
    2021-01-12 11:29

    When I have to face such a problem, I reverse the logic. I do not set a default value to an empty field, but I pre-load the field with the default value in the render part of the operation. So I can safely valid with just @DateTimeFormat(pattern="dd-MMM-yyyy") because an empty field suppose that the user indendly removed the default value which is an error.

    So IMHO you should set your default values in the GET part of you controller for that form and stick to a simple @DateTimeFormat(pattern="dd-MMM-yyyy") annotation.

    I have an application using a @ModelAttribute annotated object containing a date field. In the object class, the date field is annotated on getter and setter with DateTimeFormat(pattern="dd/MM/yyyy"). And Spring (3.2.4) accept an empty value for the date field which simply sets it to null. So you should use @DateTimeFormat(pattern="dd-MMM-yyyy") and still be able to accept null values.

提交回复
热议问题