[2.0] Validating a string for MM/DD/YYYY format
Howdy folks,
I have a string variable that should have data in it as 06/12/2007 (MM/DD/YYYY). basically a date. how can I validate if it is in the correct format. If the string variable has data in any other format say 06/12/07 (MM/DD/YY), it should throw an error.
How can I do that in C#?
thanks
nath
Re: [2.0] Validating a string for MM/DD/YYYY format
You have two choices. DateTime.TryParseExact will parse the string and return False if it fails, while ParseExact will throw an exception.
Re: [2.0] Validating a string for MM/DD/YYYY format
You can also use regular expressions:
Code:
private bool IsFormattedDate(string Expression)
{
return System.Text.RegularExpressions.Regex.IsMatch("" , @"(?<Month>([1-9])|(0[1-9])|(1[0-2]))/(?<Day>\d{2})/(?<Year>(?:\d{4}))(?x)");
}