Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC form validation Date field

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 ?

like image 608
user1459144 Avatar asked Jun 05 '14 06:06

user1459144


People also ask

How do you validate a Spring date?

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.

How do you validate a user's input within a number range in Spring MVC?

In Spring MVC Validation, we can validate the user's input within a number range. The following annotations are used to achieve number validation: @Min annotation - It is required to pass an integer value with @Min annotation. The user input must be equal to or greater than this value.


1 Answers

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.

like image 152
d3day Avatar answered Sep 18 '22 00:09

d3day