Spring MVC form validation Date field

2020-03-21 09:26发布

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

<form:input path="date" />

And I have requirement to make validation in following way:

  1. If user leaves this field es empty. I need to set some default date.

  2. If User enetered in unacceptable format, I need to present an error.

The problem is that I can meet either 1st or 2nd requirement.

  1. I can register PropertyEditor and in case date is unacceptable set null, and in case this field null set some default date. But with this approach I can't meet 2nd requirement because if I convert it to null I won't have ability to register 2nd error to user.
  2. I can set @DateTimeFormat(pattern="dd-MMM-yyyy") annotation and provide appropriate typeMismatch error but it still return this error when user leaves empty value in this field.

Is any good solution to such problem ?

2条回答
Luminary・发光体
2楼-- · 2020-03-21 10:18

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.

查看更多
▲ chillily
3楼-- · 2020-03-21 10:25

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.

查看更多
登录 后发表回答