2

I have a joda datetime attribute in my request object and I have used @DateTimeFormat for the date formatting.
But when I enter an invalid date(say day as 55), it displays the whole message

Failed to convert property value of type java.lang.String to required type org.joda.time.DateTime for property request.myDate; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "55/12/2014" from type java.lang.String to type org.joda.time.DateTime; nested exception is org.joda.time.IllegalFieldValueException: Cannot parse "55/12/2014": Value 55 for dayOfMonth must be in the range [1,31]

How can I change it to a custom message as the present message is generated by Spring.

In another SO question
Spring mvc Joda Datetime converter fail if invalid date
it is asked to make entry in message.properties.
But I'm not able to understand how will it pick the message from property file as I am not doing any error.rejectValue type of thing, So how will the message be identified.

Community
  • 1
  • 1
iAmLearning
  • 1,153
  • 3
  • 15
  • 28
  • This question is not a duplicate of http://stackoverflow.com/questions/6539884/spring-mvc-joda-datetime-converter-fail-if-invalid-date but the previous one could not solve my problem – iAmLearning Dec 30 '14 at 13:09
  • The approach in the answer you linked to should work, except you need to use key `typeMismatch.org.joda.time.DateTime`. Spring will know to use this message because it will look for `typeMismatch. + fullyQualifiedClassName` message in the configured message source. – Bohuslav Burghardt Dec 30 '14 at 13:27
  • I posted an answer based on the comment and added more detailed information to it :) – Bohuslav Burghardt Dec 31 '14 at 18:57

1 Answers1

4

The approach you linked to in your question should work. But the message key you should use is for instance typeMismatch.org.joda.time.DateTime.

Even though you are not manually rejecting the value anywhere Spring will automatically know where to look for the message based on the rules described in the JavaDoc of DefaultMessageCodesResolver.

In the situation you describe Spring will look for following codes specifically:

  1. typeMismatch.request.myDate - Conversion message for attribute named "myDate" on an object named "request"
  2. typeMismatch.myDate - Conversion message for attribute named myDate
  3. typeMismatch.org.joda.time.DateTime - Conversion message for DateTime type
  4. typeMismatch - General conversion error message

So you can define some general typeMismatch message like Incorrect format and then define more specific messages as needed. The more specific error codes have higher priority than those below it. So if you have both typeMismatch and typeMismatch.org.joda.time.DateTime messages defined, the latter will be used.

iAmLearning
  • 1,153
  • 3
  • 15
  • 28
Bohuslav Burghardt
  • 33,626
  • 7
  • 114
  • 109