我使用正则表达式来检查我的ASP.NET MVC异常中提供的日期的格式。然而,每次我运行它的时候,web服务器崩溃,Visual Studio报告和未处理的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");
}以前有没有人遇到过这个问题?
发布于 2009-08-30 11:48:30
您不需要正则表达式来检查DateTime格式,可以使用DateTime.TryParseExact方法:
将日期和时间的指定字符串表示形式转换为其DateTime等效项。字符串表示形式的格式必须与指定的格式完全匹配。此方法返回一个值,指示转换是否成功。
下面是一个如何使用它的示例:
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");
}我不确定为什么您的正则表达式会产生问题,但我认为最好在这里通过使用适当的DateTime验证解决方案来避免这个问题。
https://stackoverflow.com/questions/1353669
复制相似问题