简体   繁体   中英

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.

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);

Decorating a DateTime field with the [RegularExpression] attribute doesn't make any sense. This attribute is used with string types. When you have a DateTime property the default model binder will use the current culture setting to parse the request value into a DateTime assuming it was a POST request and it will use the yyyy-MM-dd format if it was a GET request. So as you can see it's the default model binder responsible for converting the user HTTP request into an instance of the DateTime field and the RegularExpression validator doesn't come into play.

So if you want to restrict the dates that a user can enter to some custom format you could use a custom model binder for dates.

Same stands true for other value types such as integers and doubles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM