Announcement Announcement Module
No announcement yet.
Strict Date Parsing Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Strict Date Parsing

    I have a form that requires users to input dates and an accompanying initBinder:

    protected void initBinder(RequestContext context, DataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
    dateFormat, true));
    new StringTrimmerEditor(false));

    Using this, a date with an invalid day of month (or day or year) e.g. 2008-08-32 is successfully bound by rolling forward the month (or year) to e.g. 2008-09-01. I'd like to know if there is any way of generating a binding (or validation) error when this happens.

    Many thanks,


  • #2
    You can override onBind method, where you find parameter holding binding errors. But, I'm not sure whether custom date editor throws an exception or register error or not


    • #3
      Thanks. Turns out my initBinder method wasn't doing much as it was being overridden by a propertyEditorRegistrar in a webflow FormAction. Anyway, I've managed to solve the problem by subclassing SimpleDateFormat and overriding its parse method:

      public class StrictDateFormat extends SimpleDateFormat {

      public Date parse(String arg0) throws ParseException {
      Date result = super.parse(arg0);
      String testDate = this.format(result);
      if (!arg0.equals(testDate)) {
      throw new ParseException("Date formatting result not identical to input value", 0);
      if (!allowFuture && result.after(new Date())) {
      throw new ParseException("Date in future not allowed", 0);
      return result;

      private boolean allowFuture = true;
      public void setAllowFuture(boolean allowFuture) {
      this.allowFuture = allowFuture;

      I also added an allowFuture property that will reject a future date if needed.

      Using this class instead of SimpleDateFormat in initBinder should (I guess) produce the desired result. However, in my webflow-based form this was achieved instead by using the following PropertyEditorRegistrar and injecting it into the FormAction class:

      public class UpdateDatesRegistrar implements PropertyEditorRegistrar {

      public void registerCustomEditors(PropertyEditorRegistry registry) {
      StrictDateFormat dateFormatter = new StrictDateFormat("yyyy-MM-dd");
      registry.registerCustomEditor(Date.class, new CustomDateEditor(dateFormatter, true));


      Hope that might help anyone else faced with a similar problem.



      • #4
        It's also possible (and maybe easier) to create a SimpleDateFormat instance and set lenient to false. If you enter a wrong date (like in your example), an exception will be thrown.