0

I have made the Date in in my java Class

and this is the code i have used in controller

@InitBinder
    public void initBinder(final WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyy"), true));
    }

i am usinng JSR annotations and hibernate to validate other fields.

Is there any way i can use annotations to validate that date must in dd-mm-yyyy format only

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • nice solution wasalredy discused here se http://stackoverflow.com/questions/691790/spring-validation-how-to-have-propertyeditor-generate-specific-error-message especially the answer by Arthur Ronald F D Garcia – Josef Prochazka Mar 28 '13 at 11:09

1 Answers1

2

The CustomDateEditor is not a validator itself, but in this case it does implicitly validate your pattern: it will just parse a string to a date using the format you specified. So you'll get a null value if the parsing does not succeed.

Spring validation occurs after binding, so any validation will be performed on the Date object (so after that string is parsed), not on the initial string.

Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
  • As someone already mentioned, but that answer disappeared for some reason, there's also the `org.springframework.format.annotation.DateTimeFormat` annotation that you can use on your Date field with the date pattern and it will be used by the `ConversionService`. This seems to be closer to what you're looking for. I wonder why the other answer was deleted... – Costi Ciudatu Mar 08 '11 at 09:30
  • @DateTimeFormat("dd-MM-yyyy") private Date myDate; – Costi Ciudatu Mar 08 '11 at 12:56
  • sorry, that's @DateTimeFormat(pattern = "dd-MM-yyyy") – Costi Ciudatu Mar 08 '11 at 13:20
  • hmm... it's quite strange. Can you debug it and see how the converter performs that ? The source code should tell you all you need... – Costi Ciudatu Mar 08 '11 at 14:23
  • i have tried many times that for example if i enter "1111-1111-1111" in date field and in some other field there is some other error and when the form loads again , then date is pre-loaded in with dd-mm-yyyy format . rather than giving error , it reformars it –  Mar 08 '11 at 14:49
  • How we present a better error to the user instead of 'Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property startDate; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "" ? – thisisananth Jun 14 '11 at 19:48
  • Config to use a message resolver in Spring app context like this `` `` `` Then in properties file, add a key/value for typeMismatch.userExt.profile.birthdate=Date not formatted properly – bnguyen82 Jun 26 '12 at 03:38