Spring MVC form validation Date field

后端 未结 2 1845
自闭症患者
自闭症患者 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.

    0 讨论(0)
  • 2021-01-12 11:51

    There is a way to do this if you'll move from Spring MVC validators to Hibernate. It's not a big deal because Hibernate validators work well with Spring Validator interface (also you may be interested in SmartValidator intreface which supports groups).

    After that you can specify
    @NotNull
    annotation on the date field.

    In properties file just add
    NotNull.[formName].[dateField]=This message will be displayed if no date sent typeMismatch.[formName].[dateField]=This message will be displayed if spring was not able to convert input to date object (format validation error)

    For format check you can use CustomDateEditor.

    With this solution you will get expected validation error messages in each case you've specified.

    0 讨论(0)
提交回复
热议问题