Im在ASP.net MVC項目中使用RegularExpression屬性時遇到了一些問題。使用正則表達式進行驗證
看來工作客戶端,它消失時,它適合,但在隨後的行動後,模型狀態檢查是有效的,它最終發佈的錯誤,它必須遵循的正則表達式。
我已經試過theese如下:
^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}$
^\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{1,2}$
本質上,它必須趕上14/12/2014 14:20作爲輸入。
任何想法?我迷路了。
型號:
[Required]
[Display(Name = "TimeDisplay", ResourceType = typeof(Resources.Models.Log))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
[RegularExpression(@"^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}$")]
public DateTime Time { get; set; }
控制器動作:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Log log)
{
if (ModelState.IsValid)
{
db.Logs.Add(log);
db.SaveChanges();
TempData["Notification"] = AlertGenerator.GenerateAlert(AlertGenerator.Level.Success, "Success! Log Saved");
return RedirectToAction("Index");
}
return View(log);
}
隨着您的常規表達n,'00/00/0000 99:99'是有效的輸入。你確定你想要嗎?對日期組件使用日期選擇器,對小時和分鐘組件使用下拉可能會更好。 – rikitikitik
其手動輸入,如果人們做出錯誤類型這樣吧,此刻它主要是用於輸入的正確格式,以便用戶知道它,而不是輸入東西的方式邪惡 – Zaixu
[這個答案](HTTP://計算器。 com/questions/6388238/validate-a-date-in-a-specific-format-in-asp-net-mvc-3?rq = 1)表明使用'DateExpression'驗證'DateTime'時出現問題。而[this](http://stackoverflow.com/questions/1352948/how-to-get-all-errors-from-asp-net-mvc-modelstate)爲您提供了一種方法來檢查您的驗證到底有什麼問題。現在,如果我放棄'RegularExpression'驗證並將日期格式轉換爲'{0:MM/dd/yyyy HH:mm}',我的驗證成功,這表明文化或本地化問題。 – Jasen