Announcement Announcement Module
Collapse
No announcement yet.
validate date request parameter Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • validate date request parameter

    Hi,

    My command class has a String field which holds a date parameter. An implementation of Validator checks that this string is actually a valid date, then in the controller I convert the string to a date (using basically the same code that's used for validation).

    It's pretty clear to me that this is incredibly lame, and I suspect there's probably some way that Spring can automatically convert strings to dates, before it calls the setters on a command object. If so, could someone point me towards an example?

    Thanks in advance,
    DM

  • #2
    Use org.springframework.beans.propertyeditors.CustomDa teEditor

    In your controller:

    Code:
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
    {
      SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
      binder.registerCustomEditor(Date.class, null, new CustomDateEditor(parser, false));
    }
    Passing null to registerCustomEditor will effect all bean properties which are Date objects. If you want to use different formats for different properties, then register more than one CustomDateEditor and replace null with the name of the property (the path you bound the HTML form input to).

    Mike

    Comment


    • #3
      Thanks for the suggestion. However, in my case the request parameter is optional. If it is not provided, the conversion fails with the error message:

      Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property 'birthDate'; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "null"

      Is it possible to make this work for optional parameters?

      Cheers,
      DM

      Comment


      • #4
        Yep, pass true as the 2nd argument to CustomDateEditor's constructor

        Comment

        Working...
        X