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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With