首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ASP.NET MVC中使用正则表达式时未处理的System.StackOverflowException

在ASP.NET MVC中使用正则表达式时未处理的System.StackOverflowException
EN

Stack Overflow用户
提问于 2009-08-30 11:21:02
回答 1查看 1.1K关注 0票数 0

我使用正则表达式来检查我的ASP.NET MVC异常中提供的日期的格式。然而,每次我运行它的时候,web服务器崩溃,Visual Studio报告和未处理的System.StackOverflowException

代码语言:javascript
复制
//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");
}

以前有没有人遇到过这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2009-08-30 11:48:30

您不需要正则表达式来检查DateTime格式,可以使用DateTime.TryParseExact方法:

将日期和时间的指定字符串表示形式转换为其DateTime等效项。字符串表示形式的格式必须与指定的格式完全匹配。此方法返回一个值,指示转换是否成功。

下面是一个如何使用它的示例:

代码语言:javascript
复制
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验证解决方案来避免这个问题。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1353669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档