Spring MVC使用JSR303进行日期格式验证 [英] Spring MVC Date format validation with JSR303
问题描述
我创建的表单有几个绑定到$的日期字段c $ c> Date 对象中的对象支持表单。我正在使用JSR303使用 @Future
对 Date
进行验证。我也使用 @DateTimeFormat(pattern =dd / MM / yyyy)
,(我知道这不是验证)。
如何验证表单上的 String
的日期格式?如果我将其他必填字段留空( @NotEmpty
),并以dd / MM / yy的形式输入无效的日期,则将其转换为dd / MM / yyyy'重新呈现(例如12/03/12被重新呈现为12/03/0012)。这意味着我将在系统中获取数据。如果我输入aaa,我得到一个转换异常。正确格式化 String
s转换为 Date
对象。
此外, Date
字段的必填字段注释是 @NotNull
或 @NotEmpty
?
非常感谢提供的任何建议。
感谢拉尔夫。我做了一些进一步的挖掘,并提出了(这在我的表单控制器):
@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);
}
属性文件具有以下密钥:
typeMismatch.java.util.Date
:有些不错的平静安心的消息来帮助所有疏忽的用户
也许还有其他一些方法可以做到这一点,但是现在这样做。
I'm using Spring MVC with JSR303 to do my input validation.
A form I've created has a couple of date fields that are bound to Date
objects within the object backing the form. I'm using JSR303 to do the validation for the Date
using @Future
. I'm also using @DateTimeFormat(pattern="dd/MM/yyyy")
, (I know it's not validation).
How do I validate the date format of the String
on the form? 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 (e.g. 12/03/12 is re-presented as 12/03/0012). Which means I will get duff data in my system. If I enter "aaa" for I get a conversion Exception. Correctly formatted String
s get converted to Date
objects.
Additionally should the 'required field' annotation for Date
fields be @NotNull
or @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
Maybe there are some other ways to do this but this will do for now.
这篇关于Spring MVC使用JSR303进行日期格式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!