title: Validate a Date in a specific format in ASP.NET MVC 3
body: <p>I have a property of type <code>DateTime MyDate</code> in my ViewModel. I want to make sure that the user only enters the Date part in a text box in a specific format (dd.mm.yyyy) and tried the following attributes:</p>
  
  <pre><code>[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode=true)]
  [RegularExpression(@"^(([0-2]\d|[3][0-1])\.([0]\d|[1][0-2])\.[2][0]\d{2})$",
      ErrorMessage="Failed...")]
  public DateTime MyDate { get; set; }
  </code></pre>
  
  <p>The controller action signature for a HttpPost looks like this:</p>
  
  <pre><code>[HttpPost]
  public ActionResult Edit(int id, MyViewModel viewModel)
  {
      // MyViewModel contains the MyDate property ...
      // ...
      if (ModelState.IsValid)
      {
          // ...
      }
      // ...
  }
  </code></pre>
  
  <p>In the Razor view I tried the following two ways:</p>
  
  <ol>
  <li><p><code>@Html.TextBoxFor(model =&gt; model.MyDate)</code></p></li>
  <li><p><code>@Html.EditorFor(model =&gt; model.MyDate)</code></p></li>
  </ol>
  
  <p>It doesn't work as I want. The result is:</p>
  
  <ul>
  <li>Client side validation works as expected with both Html helpers</li>
  <li>Server side validation always fails for both helpers, even with valid dates like "17.06.2011" which pass the regular expression. The <code>MyDate</code> property is filled correctly with the entered date in <code>viewModel</code> which is passed to the action. So it seems that model binding was working.</li>
  <li>The <code>DisplayFormat</code> attribute is only respected by <code>EditorFor</code> but not by <code>TextBoxFor</code>. <code>TextBoxFor</code> displays "dd.mm.yyyy hh:mm:ss"</li>
  </ul>
  
  <p>Questions:</p>
  
  <ol>
  <li><p>Can I apply a <code>RegularExpressionAttribute</code> at all on a property which isn't a <code>string</code>? If it is allowed how is the reg ex evaluated for a non-string property like <code>DateTime</code> on server side? Is something like <code>MyDate.ToString()</code> compared with the reg ex? (It would explain that the validation fails because ToString will return a string including time part which doesn't pass the regular expression.)</p></li>
  <li><p>Is the <code>DisplayFormat</code> attribute generally only respected by <code>EditorFor</code> and never by <code>TextBoxFor</code>?</p></li>
  <li><p>How can I do a date validation right?</p></li>
  </ol>