问题描述
我有一个表单域应该被转换为一个Date对象,如下所示:
< form:input path =date/>
我有以下要求进行验证:
-
如果用户离开此字段为空。我需要设置一些默认日期。
-
如果用户以不可接受的格式输入,我需要提交一个错误。
问题是我可以满足第1或第2个要求。
- 我可以注册 PropertyEditor ,如果日期不可接受,则设置为null,并且如果此字段为空,则设置一些默认日期。但是使用这种方法我不能满足第二个要求,因为如果我把它转换为空我无法向用户注册第二个错误。
- 我可以设置 @DateTimeFormat (pattern =dd-MMM-yyyy)注释,并提供适当的类型不匹配错误,但是当用户在此字段中留下空值时仍会返回此错误。
有没有什么好的解决方案?
有一种方法可以做到这一点,如果你将从Spring MVC验证器移到Hibernate。这不是一件大事,因为Hibernate验证器与Spring Validator接口工作良好(您也可能对支持组的SmartValidator intreface感兴趣)。
之后,您可以指定
@NotNull
注释在日期字段中。
在属性文件中只需添加
NotNull。[formName]。[dateField]
=如果没有发送日期
typeMismatch。[formName]。[dateField]
=将显示此消息如果春天不是能够将输入转换为日期对象(格式验证错误)
对于格式检查,您可以使用 CustomDateEditor
p>
使用此解决方案,您将在每种情况下获得预期的验证错误消息。
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.
- 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.
- 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 ?
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 senttypeMismatch.[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.
这篇关于Spring MVC表单验证日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!