简体   繁体   中英

Regular expression to validate date - C#

I am using a calenderExtender control to get a date from user. The text box can be edit manually by the user. I am using a RegularExpressionValidator to validate Input date. The input format i need is

MMM dd, yyyy

Now i am using a regular expression shown below to validate date

  ((Jan)|(Feb)|(Mar)|(Apr)|(May)|(Jun)|(Jul)|(Aug)|(Sep)|(Oct)|(Nov)|(Dec)){1}\s?\d{1,2},\s?\d{4}

It works fine. But it do not check the input date is less than 28,30 or 31 based on month . example :the month December have 31 days. If the user entered greater than 31 ,the expression must caught that. Any ideas to achieve this using regular exptression??

The validation that you want to do (excluding invalid date ranges based on month) is really unsuited for a regular expression. You should parse the month, date, and year, and then do your validation based on the parsed values. Trying to do it via a regex will be painful and difficult to maintain.

Alternately, have you considered just using DateTime.Parse ?

If you think that's bad, just wait till you try supporting leap years. Yep, as is usually the case with "how do I do (insert difficult task) with regex?" questions, the best approach is to just avoid regular expressions entirely. Can you use a RangeValidator instead? Otherwise, as JSBangs noted, you could use a custom validator with DateTime's parsing methods.

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