【问题标题】:How to specify custom validate error message in SimpleDateFormat using Spring MVC如何使用 Spring MVC 在 SimpleDateFormat 中指定自定义验证错误消息
【发布时间】:2014-07-10 13:28:26
【问题描述】:

在我的 Smpring MVC 应用程序中,我使用 SimpleDateFormat 作为 WebDataBinder 中的自定义编辑器来验证日期。当输入的日期与所需的模式不匹配时,我会在表单中收到原始错误消息:错误标记,例如:

Failed to convert property value of type java.lang.String to required type java.util.Date for property hireDate; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "432345"

我的问题是我想在 jsp 页面上显示自定义错误消息,例如:

“出生日期必须符合“dd/MM/yyyy”模式”

这是我的@InitBinder 的代码:

@InitBinder
protected void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}

谢谢。

【问题讨论】:

    标签: java validation spring-mvc simpledateformat spring-mvc-initbinders


    【解决方案1】:

    这可能不是您想要的,但在我们的命令中,我们使用字符串来表示(几乎)我们所有的属性。

    然后我们对这些字符串进行验证,看看它们是否会成为我们在访问命令时希望的数据类型。

    【讨论】:

      【解决方案2】:

      尝试在您的消息包中注册以下消息:

      typeMismatch.command.field=Date of birth must match "dd/MM/yyyy" pattern
      or
      typeMismatch.field = ...
      

      用适当的命令对象替换命令和字段

      更多细节在这里: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/DefaultMessageCodesResolver.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-21
        • 1970-01-01
        • 1970-01-01
        • 2011-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多