[英]Spring MVC Date format validation with JSR303
I'm using Spring MVC with JSR303 to do my input validation. 我正在使用带有JSR303的Spring MVC进行输入验证。
A form I've created has a couple of date fields that are bound to Date
objects within the object backing the form. 我创建的表单有几个日期字段绑定到支持表单的对象中的
Date
对象。 I'm using JSR303 to do the validation for the Date
using @Future
. 我正在使用JSR303使用@Future对
Date
进行@Future
。 I'm also using @DateTimeFormat(pattern="dd/MM/yyyy")
, (I know it's not validation). 我也在使用
@DateTimeFormat(pattern="dd/MM/yyyy")
,(我知道这不是验证)。
How do I validate the date format of the String
on the form? 如何验证表单上
String
的日期格式? If I leave the other required fields blank ( @NotEmpty
) and enter a non-valid date in the form 'dd/MM/yy' it gets converted to 'dd/MM/yyyy' on re-presentation (eg 12/03/12 is re-presented as 12/03/0012). 如果我将其他必填字段留空(
@NotEmpty
)并以'dd / MM / yy'形式输入无效日期,则会在重新呈现时转换为'dd / MM / yyyy'(例如12/03 / 12表示为12/03/0012)。 Which means I will get duff data in my system. 这意味着我将在我的系统中获取duff数据。 If I enter "aaa" for I get a conversion Exception.
如果输入“ aaa”,则将获得转换异常。 Correctly formatted
String
s get converted to Date
objects. 格式正确的
String
将转换为Date
对象。
Additionally should the 'required field' annotation for Date
fields be @NotNull
or @NotEmpty
? 另外,
Date
字段的'required field'注释是@NotNull
还是@NotEmpty
?
Many thanks in advance for any advice provided. 非常感谢您提供的任何建议。
Thanks Ralph. 谢谢拉尔夫。 I did some further digging around and came up with this (Which goes in my form controller):
我做了一些进一步的挖掘,并提出了这个建议(在我的表单控制器中):
@InitBinder
public void initBinder(WebDataBinder binder) {
String format = "dd/MM/yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
CustomDateEditor customDateEditor = new CustomDateEditor(dateFormat,true,format.length());
binder.registerCustomEditor(Date.class, customDateEditor);
}
With the properties file having the following key: 使用具有以下键的属性文件:
typeMismatch.java.util.Date
: Some nice calm reassuring message to assist all negligent users typeMismatch.java.util.Date
:一些不错的平静的令人放心的消息,可以帮助所有过失的用户
Maybe there are some other ways to do this but this will do for now. 也许还有其他一些方法可以做到这一点,但现在这样做。
You can not do this with JSR303, because the validation runs on the already poplulated (form baching) object. 你无法用JSR303做到这一点,因为验证是在已经流行的(表单缓存)对象上运行的。
So you need to implement your own custom converter, that is a bit more strickt than the one shipped with spring. 因此,您需要实现自己的自定义转换器,这比弹簧附带的转换器要严格得多。
@See Spring Reference: Chapter 6.5 Spring 3 Type Conversion @参见Spring参考:第6.5章Spring 3类型转换
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.