4

i needed a function for validate the entered date. whether entered date is in correct format. i browsed the web and got a regular expression for it. Its works fine except when you enter 12/12/YYYY(on any year) it shows error saying that its not a valid date.

bool IsDate(string date) { Match dobMatch = Regex.Match(date, @"^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$"); if (!dobMatch.Success) {return true;} else {return false;} } 

i

4 Answers 4

6

Try DateTime.TryParse().

This parses dates for you. This method allows you to pass the CultureInfo if the culture you want to use to parse the date with.

Alternatively, if you really want to use regular expressions, have a look at http://regexlib.com/. That is a comprehensive library of regular expressions with ratings per regular expression.

Sign up to request clarification or add additional context in comments.

2 Comments

Did the function mentioned validates the date whether exist or not in feburary also like 30/2/2011
Yes. It can only produce (the out parameter) a valid date, including leap years.
2

Why don't you use DateTime.TryParse or DateTime.TryParseExact far easier than using a Regex.

1 Comment

Did the function mentioned validates the date whether exist or not in feburary also like 30/2/2011
1

A regular expression only validates the character data in a string and does not say anything about the actual validity of the data in that string.

To check a string as a valid date in .Net use the following:

DateTime dt; if (DateTime.TryParse(someString, out dt)) { //Parsed as a valid date whose value is now in the variable dt } else { //Not a valid date } 

2 Comments

Did the function mentioned validates the date whether exist or not in feburary also like 30/2/2011
Yes it does, if the date is not valid then TryParse will return false
1

Use:

^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$ 

Or go to following link , http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.