使用 JSR303 验证 Spring MVC 日期格式

2022-01-15 00:00:00 format date java spring-mvc bean-validation

我正在使用带有 JSR303 的 Spring MVC 进行输入验证.

I'm using Spring MVC with JSR303 to do my input validation.

我创建的表单有几个日期字段,这些字段绑定到支持表单的对象中的 Date 对象.我正在使用 JSR303 使用 @FutureDate 进行验证.我也在使用 @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.

相关文章