java - 如何使用 Spring MVC 在 SimpleDateFormat 中指定自定义验证错误消息

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

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

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));
}

谢谢。

最佳答案

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

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

关于java - 如何使用 Spring MVC 在 SimpleDateFormat 中指定自定义验证错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23791078/

相关文章:

java - 如何根据 JList 中选择的内容更新 JLabel

java - 解决 Vaadin maven 项目中的 java.lang.ClassNotFoundException : com. vaadin.terminal.gwt.server.ApplicationServlet

hibernate - Grails not-null属性在验证期间引用了null或 transient 值

entity-framework - "Validation failed for one or more entities. See ' EntityValidationErrors 属性的解决方案以获取更多详细信息。”

spring-mvc - 用 RequestMappingHandlerAdapter 问题替换 AnnotationMethodHandlerAdapter

java - Spring Tool Suite:“属性”中的“部署程序集”选项

java - CircularArrayQueue 类中的 Enqueue 方法

java - Android/Java 类事件

regex - 如何验证美国社会保险号?

spring - 使用 spring Controller 和不同的类在 jsp 中渲染数据