views:

220

answers:

1

Hey

I'm using a regular expression to check the format of a supplied date in my ASP.NET MVC exception. However, every time I run it the action the web server crashes and Visual Studio reports and unhandled System.StackOverflowException

//If the supplied date does not match the format yyyy-mm-dd
//Regex taken from www.regexlib.com
if(!Regex.Match(date, "^((((19|20)(([02468][048])|([13579][26]))-02-29))|((20[0-9][0-9])|(19[0-9][0-9]))-((((0[1-9])|(1[0-2]))-((0[1-9])|(1\\d)|(2[0-8])))|((((0[13578])|(1[02]))-31)|(((0[1,3-9])|(1[0-2]))-(29|30)))))$").Success)
{
    ModelState.AddModelError("Date", "Date is in an invalid format. It must in the format yyyy-mm-dd");
}

Has anybody come across this before?

+3  A: 

You don't need a regular expression to check DateTime formats, use the DateTime.TryParseExact method:

Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly. The method returns a value that indicates whether the conversion succeeded.

Here is an example of how to use it:

DateTime dateTime;

if (!DateTime.TryParseExact(
    yourString, 
    "yyyy-MM-dd", 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None, 
    out dateTime))
{
     ModelState.AddModelError(
      "Date", 
      "Date is in an invalid format. It must in the format yyyy-mm-dd");
}

I am not sure why your regular expression is creating problems but I think it would be best to avoid the problem all together here by using the proper solution for DateTime validation.

Andrew Hare
D'oh! I'd used that method somewhere else before too. Don't know why I didn't think to use it here. Thanks.