1

I'm using Spring MVC with JSR303 to do my input validation.

A form I've created has a couple of date fields that are bound to Date objects within the object backing the form. I'm using JSR303 to do the validation for the Date using @Future. I'm also using @DateTimeFormat(pattern="dd/MM/yyyy"), (I know it's not validation).

How do I validate the date format of the String on the form? If I leave the other required fields blank (@NotEmpty) and enter a non-valid date in the form 'dd/MM/yy' it gets converted to 'dd/MM/yyyy' on re-presentation (e.g. 12/03/12 is re-presented as 12/03/0012). Which means I will get duff data in my system. If I enter "aaa" for I get a conversion Exception. Correctly formatted Strings get converted to Date objects.

Additionally should the 'required field' annotation for Date fields be @NotNull or @NotEmpty?

Many thanks in advance for any advice provided.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Sausage
  • 71
  • 2
  • 5

2 Answers2

2

Thanks Ralph. I did some further digging around and came up with this (Which goes in my form controller):

    @InitBinder
    public void initBinder(WebDataBinder binder) {


    String format = "dd/MM/yyyy";
    SimpleDateFormat dateFormat = new SimpleDateFormat(format);
    dateFormat.setLenient(false);
    CustomDateEditor customDateEditor = new CustomDateEditor(dateFormat,true,format.length());

    binder.registerCustomEditor(Date.class, customDateEditor);
    }

With the properties file having the following key:

typeMismatch.java.util.Date : Some nice calm reassuring message to assist all negligent users

Maybe there are some other ways to do this but this will do for now.

vdenotaris
  • 13,297
  • 26
  • 81
  • 132
Sausage
  • 71
  • 2
  • 5
  • Is it possible to change message key from typeMismatch.java.util.Date to something more specific like CommandObjectXYZ.dateXYZ=Date is not valid – svlada Nov 07 '12 at 08:59
1

You can not do this with JSR303, because the validation runs on the already poplulated (form baching) object.

So you need to implement your own custom converter, that is a bit more strickt than the one shipped with spring.

@See Spring Reference: Chapter 6.5 Spring 3 Type Conversion

Ralph
  • 118,862
  • 56
  • 287
  • 383