Spring MVC Date format validation with JSR303(使用 JSR303 验证 Spring MVC 日期格式)
问题描述
我正在使用带有 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 Strings 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 日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JSR303 验证 Spring MVC 日期格式
基础教程推荐
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
