title: How to validate date format in a Spring form
body: <p>I'm new to Spring, and I'm trying to create a form that validates a date format (i.e.: it accepts only dates with the format "<code>MM/dd/yyyy</code>" if the user puts "<code>mm-dd-yyyy</code>" it should show an error message). </p>
  
  <p>How can I achieve this with Spring?</p>
  
  <p>I have read a lot of posts and answers like <a href="https://stackoverflow.com/questions/9352891/spring-mvc-date-format-validation-with-jsr303">this</a> and <a href="https://stackoverflow.com/questions/10785107/set-date-format-for-an-input-text-using-spring-mvc">this</a>, that recommend using the <code>@InitBinder</code> in the controller (I tried but couldn't make it work btw). But what if I have a form with different dates? or if my controller manages multiple post request from different forms, and each one requires different dates validations?</p>
  
  <p>Currently I have this form:</p>
  
  <pre><code>&lt;form:form action="getReportFile.html" commandName="staticReportForm"&gt;
              &lt;table&gt;
                  &lt;tr&gt;
                      &lt;td&gt;Reports:&lt;/td&gt;
                  &lt;/tr&gt;
                  &lt;tr&gt;
                      &lt;td&gt;&lt;form:select path="report" items="${staticReports}"/&gt;                        
                      &lt;/td&gt;
                  &lt;/tr&gt;
                 &lt;tr&gt;
                     &lt;td&gt;Date (MM/DD/YYYY) (empty for most recent possible):&lt;FONT color="red"&gt;&lt;form:errors
                                  path="date" /&gt;&lt;/FONT&gt;&lt;/td&gt;
                 &lt;/tr&gt;
                 &lt;tr&gt;
                     &lt;td&gt;&lt;form:input path="date" /&gt;&lt;/td&gt;
                 &lt;/tr&gt;
                 &lt;tr&gt;
                     &lt;td&gt;&lt;input type="submit" value="Submit" /&gt;&lt;/td&gt;
                 &lt;/tr&gt;
             &lt;/table&gt;            
         &lt;/form:form&gt;
  </code></pre>
  
  <p>And this would be the bean backing the form (the <code>@DateTimeFormat</code> annotation only make it work if you put the correct format):</p>
  
  <pre><code>public class StaticReportForm {
          @NotEmpty        
          private String report;    
          @DateTimeFormat(pattern="MM/dd/yyyy")
          private Date date;
  
      public String getReport() {
          return report;
      }
  
      public void setReport(String report) {
          this.report = report;
      }
  
      public Date getDate() {
          return date;
      }
  
      public void setDate(Date date) {
          this.date = date;
      }
  
  
  }
  </code></pre>