簡體   English   中英

在ASP.NET MVC中使用正則表達式時未處理的System.StackOverflowException

[英]Unhandled System.StackOverflowException when using regex in ASP.NET MVC

我正在使用正則表達式來檢查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");
}

有人遇到過嗎?

您不需要正則表達式來檢查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驗證解決方案來避免所有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM