I have an Entity Frameworks POCO that has a property defined like this:
[RegularExpression(ValidationHelper.RegularExpressionForDateOnly)]
public virtual DateTime LastBuildDate { get; set; }
Where the constant is defined like this:
public const String RegularExpressionForDateOnly =
@"^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$";
I got that regex right from OWASP: https://www.owasp.org/index.php/OWASP_Validation_Regex_Repository
Now, on the MVC3 view, I have:
<tr>
<td class="editor-label">
@Html.LabelFor(model => model.LastBuildDate)
</td>
<td class="editor-field">
@Html.EditorFor(model => model.LastBuildDate)
@Html.ValidationMessageFor(model => model.LastBuildDate)
</td>
</tr>
When I try to put a date in the format of “05/30/2012” or “5/30/2012”, it fails validation (client and server-side). If I manually try that regular expression, that regular expression SHOULD allow those formats. However, when the MVC3 view is validating with it, it fails validation.
What other reason would there be for the MVC to fail this regex validation?
I dont know enough about regex to tell you exactly what your doing wrong, but when it comes to MVC3 validators, I definitely recommend the Data Annotations Extension you can find it on Nuget too.
It adds a bunch of validation attributes including date validation.