Spring MVC表单验证日期字段 [英] Spring MVC form validation Date field

查看:471
本文介绍了Spring MVC表单验证日期字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单域应该被转换为一个Date对象,如下所示:

 < form:input path =date/> 

我有以下要求进行验证:


  1. 如果用户离开此字段为空。我需要设置一些默认日期。


  2. 如果用户以不可接受的格式输入,我需要提交一个错误。


问题是我可以满足第1或第2个要求。


  1. 我可以注册 PropertyEditor ,如果日期不可接受,则设置为null,并且如果此字段为空,则设置一些默认日期。但是使用这种方法我不能满足第二个要求,因为如果我把它转换为空我无法向用户注册第二个错误。

  2. 我可以设置 @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:

  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 ?

解决方案

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.

这篇关于Spring MVC表单验证日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆