title: Binding of Custom Formatted TimeSpan Using DataAnnotations
body: <p>I'm building an ASP.Net Core 2.1 MVC web app using EF Core. I have a model which has a <code>TimeSpan</code> property. I want the entered time (mm:ss) to be between <code>01:00</code> and <code>59:59</code>, so I do not want to show the hours part of the TimeSpan, as it is zero in any case. To achieve this, I added <code>DisplayFormat</code> attribute to my property. Because I want working client-side validation, I added a <code>RegularExpression</code> attribute too:</p>
  
  <pre><code>[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:mm\:ss}")]
  [RegularExpression(@"((0?0:)?([0-3]?[0-9])(:[0-5][0-9])?)", ErrorMessage = "Die Dauer muss zwischen 01:00 und 30:00 liegen")]
  public TimeSpan SlotDuration { get; set; }
  </code></pre>
  
  <p>(I do know that my regex does not validate the <em>at least one minute thing</em>, but thats not my point.)</p>
  
  <p>Now I do observe the following:</p>
  
  <ol>
  <li>When loading my <em>Edit</em> page for an entity with 20 minutes slot duration, <code>20:00</code> is shown as expected. If I submit the request, model validation fails with my regex attribute's ErrorMessage.</li>
  <li>Doing the same thing as in (1) but entering <code>0:20:00</code> works, <code>ModelState.IsValid == true</code> and the SlotDuration bound value is correct.</li>
  <li>If I remove the regex attribute, the validation and binding works correctly for <code>0:20:00</code>; using <code>20:00</code> results in a 20 hour timespan.</li>
  <li><p>The following code outputs
  <code>20:00 --&gt; 00:20:00</code> <code>match</code></p>
  
  <pre><code>string value = null;
  TimeSpan interval;
  var rg = new System.Text.RegularExpressions.Regex(@"((0?0:)?([0-3]?[0-9])(:[0-5][0-9])?)");
  value = "10:25";
  if (TimeSpan.TryParseExact(value, @"mm\:ss", null, out interval))
      Console.WriteLine("{0} --&gt; {1}", value, interval.ToString("c"));
  else
      Console.WriteLine("Unable to parse '{0}'", value);
  if (rg.IsMatch(value))
      Console.WriteLine("match");
  else
      Console.WriteLine("no match");
  </code></pre></li>
  </ol>
  
  <p>Questions:</p>
  
  <ul>
  <li>Why does the validation fail even though the regex does match and the string can be parsed as TimeSpan, even though not in the way I want?</li>
  <li>How can I make the ModelBinder use my <code>DisplayFormat</code> for converting the entered value to the TimeSpan? Is there another property/attribute/... which achieves this?</li>
  </ul>