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:
If user leaves this field es empty. I need to set some default date.
If User enetered in unacceptable format, I need to present an error.
The problem is that I can meet either 1st or 2nd requirement.
Is any good solution to such problem ?
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.
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.
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 addNotNull.[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With