How to specify custom validate error message in SimpleDateFormat using Spring MVC

3.2k views Asked by At

In my Smpring MVC application I'm validating dates using SimpleDateFormat as a custom editor in WebDataBinder. When entered date does not match required pattern I get raw error message in my form:errors tag like:

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"

My problem is that I want to display on jsp page custom error message something like:

"Date of birth must match "dd/MM/yyyy" pattern"

Here is the code of my @InitBinder:

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

Thanks.

2

There are 2 answers

0
Biju Kunjummen On BEST ANSWER

Try registering the following message in your message bundle:

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

replace command and field with appropriate command object

More details here: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/DefaultMessageCodesResolver.html

0
hooknc On

This might not be what you're looking for, but in our Commands we use Strings for (almost) all our attributes.

We then perform validation on those strings to see if they will become the data type we're hoping for when we access the command.