Dim*_*San 4 java validation spring
我正在使用带有自定义消息的Bean验证API进行表单验证:
@NotNull(message = "Please enter your birthday.")
@DateTimeFormat(pattern = "MM/dd/yyyy")
@Past(message = "That's impossible.")
private Date birthday;
Run Code Online (Sandbox Code Playgroud)
一切工作良好,直到我输入了错误的日期格式。然后,我的页面上出现了这么长而冗长的错误消息:
Failed to convert property value of type [java.lang.String] to required type
[java.util.Date] for property birthday; nested exception is
bla-bla-bla...
Run Code Online (Sandbox Code Playgroud)
由于没有来自的字段message,因此无法像其他注释一样在此添加消息。@interface DateTimeFormatorg.springframework.format.annotation.DateTimeFormat
我该如何指定自定义消息"Please use MM/dd/yyyy format"?
您将必须使用MessageSource bean和messages.properties文件,然后可以在其中添加键值,如下所示。
typeMismatch=Please use MM/dd/yyyy format
Run Code Online (Sandbox Code Playgroud)
如果您使用的是SpringBoot,则默认情况下,MessageSource bean将可用,您只需要在messages.properties中添加键值。对于普通的Spring应用程序,您可以使用ReloadableResourceBundleMessageSource或ResourceBundleMessageSource。
属性键按以下顺序解析。
typeMismatch.[form].[property]
typeMismatch.[form]
typeMismatch
Run Code Online (Sandbox Code Playgroud)
请参阅http://jtuts.com/2014/11/09/validating-dates-in-spring-form-objects/
| 归档时间: |
|
| 查看次数: |
3331 次 |
| 最近记录: |