Click here to Skip to main content
15,900,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an MVC 5.2 app in VS 2015, working with SQL Server 2016.

I have a field called Assessment_Date, which is defined in the database as a varchar(10), not as a Date, as I only want to work with the date and not the time.

I want to require the users to enter a date in the form: mm/dd/yyyy

In my partial class, I have the following lines pertinent to this field:

[RegularExpression(@"/^\d{2}\/\d{2}\/\d{4}$/")]
public string Assessment_Date { get; set; }


and in the Edit view, I have the following validation message line:

@Html.ValidationMessageFor(model => model.Assessment_Date, "mm/dd/yyyy", new { @class = "text-danger" })

The result is that it fails everything I type into the box, even if it's a correctly formatted date, like 01/02/2017.

I checked the RegularExpression on Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^] and the RegularExpression is allowing correctly-formatted dates like the one above.

What might be the reason why this RegularExpression is failing in MVC? I placed the @ sign before the quotes containing the RegularExpression; otherwise, it complains about unrecognized escape codes. I've had trouble in the past with RegularExpressions too. Is there some trick to getting them to work with MVC? Thanks.

What I have tried:

RegularExpression to format date string to mm/dd/yyyy
See above.
Posted
Updated 2-Jan-17 13:56pm

1 solution

Try:
[RegularExpression(@"^\d{2}/\d{2}/\d{4}$")]


Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 
Comments
Member 12824529 2-Jan-17 23:52pm    
Thanks. Your Regular Expression works perfectly.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900