Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for date not working; MVC3 DataAnnotations

Im using DataAnnotations in an interface of a linq sql class. Thats all fine.

Im having problems with the date time fields

My code is as follows:

 [DataType(DataType.Date)]
    [RegularExpression(@"^([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$", ErrorMessage = "regexFail")]
    DateTime? DateofBirth { get; set; }

Now the datatype expression works fine, it brings in a date rather than a date time. The problem lies in validation of the fields. My regex doesn't match dates, even though i put it into an engine and it does. For instance i put "10/10/2010" in the field and i get the error "regexFail".

I'm fairly sure my expression is good, so I'm not sure whats wrong.

Thanks in advance.

like image 414
MrJD Avatar asked Jul 13 '26 22:07

MrJD


1 Answers

I think what is happening is that the DateTime value is being converted to a string, then matched against the pattern. If that's the case, and ToString is being used, then a default time of 12:00:00 AM would be included in the string being matched.

I tried the following code and IsValid returned true:

string pattern = @"^([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d\s12:00:00\sAM$";

RegularExpressionAttribute attribute = new RegularExpressionAttribute(pattern) { ErrorMessage = "regexFail" };
DateTime dt = new DateTime(2010, 10, 10);

bool isValid = attribute.IsValid(dt);
like image 154
Jeff Ogata Avatar answered Jul 15 '26 11:07

Jeff Ogata