在我的測試應用程序,我有一個日期時間字段定義爲這樣:日期時間接受超過4個位數的年
[Required(ErrorMessage = "This is required")]
[Display(Name = "test date:")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MMMM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? date1 { get; set; }
在我看來:
@Html.EditorFor(
model => model.date1,
new {
htmlAttributes = new {
@Value = Model.date1 != null ? Model.date1.Value.ToString("yyyy-MM-dd") : ""
}
})
@Html.ValidationMessageFor(model => model.date1, "", new { @class = "text-danger" })
一切工作正常,但是當我進入像10/03/19999(dd,MM,yyyyy)這樣的日期,應用程序中斷,顯然我輸入的日期是錯誤的,但我不知道如何處理錯誤。我試過使用datetime.tryparse來回傳失敗,但後來我失去了填充表單的內容。
更新:
繼quadzz的解決方案,我已經試過:
[Required(ErrorMessage = "This is required")]
[Display(Name = "test date:")]
[DataType(DataType.Date)]
[Range(typeof(DateTime), "1/1/1900", "31/12/2000", ErrorMessage = "Value for {0} must be between {1} and {2}")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
,但它仍然無法正常工作。
爲什麼它錯了?確定它將會是一個很長的時間,然後才能達到10000但是有一天.. – BugFinder
定義「應用程序中斷」 – Charleh
「DateTime」支持年份最高達到9999。如果年份多於此值,則認爲溢出(並且可能會拋出例外)。你可以創建一個類似'DateTime'的自定義結構,其中包含5位'Year'屬性,但似乎需要在結構中聲明幾個'DateTime'方法。 –