Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom error message in org.springframework.format.annotation.DateTimeFormat?

I'm doing a form validation using Bean Validation API with my custom messages:

@NotNull(message = "Please enter your birthday.")
@DateTimeFormat(pattern = "MM/dd/yyyy")
@Past(message = "That's impossible.")
private Date birthday;

Everything works good until I put wrong date format. Then I got such a long and verbose error message on my page:

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...

As there is no field message in @interface DateTimeFormat from org.springframework.format.annotation.DateTimeFormat I cannot add my message there as I did with other annotations.

How can I specify custom message like "Please use MM/dd/yyyy format" there?

like image 428
DimaSan Avatar asked Sep 29 '16 19:09

DimaSan


2 Answers

You will have to use MessageSource bean and messages.properties file and there you can add key-value like below.

typeMismatch=Please use MM/dd/yyyy format

If you are using SpringBoot then MessageSource bean will be available by default and you only need to add key-value in messages.properties. For normal Spring application you can use ReloadableResourceBundleMessageSource or ResourceBundleMessageSource.

Property key is resolved in following order.

typeMismatch.[form].[property] 
typeMismatch.[form]
typeMismatch

Please refer http://jtuts.com/2014/11/09/validating-dates-in-spring-form-objects/

like image 66
abaghel Avatar answered Nov 11 '22 02:11

abaghel


The correct way to add custom error message is through DefaultMessageCodeResolver You can use the resolver to bind errors at object + field level(typeMismatch.YourClassName.birthday = custom message.) as mentioned in the javadoc.

Find a detailed usage here

like image 27
Akash Mishra Avatar answered Nov 11 '22 04:11

Akash Mishra