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?
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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With