問題描述
我正在使用帶有 JSR303 的 Spring MVC 進行輸入驗證.
I'm using Spring MVC with JSR303 to do my input validation.
我創建的表單有幾個日期字段,這些字段綁定到支持表單的對象中的 Date
對象.我正在使用 JSR303 使用 @Future
對 Date
進行驗證.我也在使用 @DateTimeFormat(pattern="dd/MM/yyyy")
,(我知道這不是驗證).
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).
如何驗證表單上 String
的日期格式?如果我將其他必填字段留空 (@NotEmpty
) 并以dd/MM/yy"形式輸入無效日期,它會在重新轉換為dd/MM/yyyy"演示文稿(例如 12/03/12 重新呈現為 12/03/0012).這意味著我將在我的系統中獲得 duff 數據.如果我輸入aaa",我會得到一個轉換異常.格式正確的 String
被轉換為 Date
對象.
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.
Date
字段的必填字段"注釋還應該是 @NotNull
還是 @NotEmpty
?
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);
}
屬性文件具有以下鍵:
typeMismatch.java.util.Date
:一些很好的平靜的安慰信息,以幫助所有疏忽的用戶
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.
這篇關于使用 JSR303 驗證 Spring MVC 日期格式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!