簡體   English   中英

使用ViewModel中的DataAnnotations在ASP.NET MVC中進行日期驗證

[英]Date validation in ASP.NET MVC with DataAnnotations in ViewModel

我的頁面的ViewModel中有一個DateTime屬性。 我想知道是否有內置的檢查用戶輸入有效日期的方法。

以下是我當前代碼的樣子,截至目前,它不會自動確保用戶輸入有效日期(只需要驗證):

ViewModel屬性:

[Required]
[DataType(DataType.Date)]
public DateTime MyDate{ get; set; }

Razor MVC6觀點:

<label asp-for="MyDate" class="control-label"></label>
<input asp-for="MyDate" class="form-control" />
<span asp-validation-for="MyDate" class="text-danger" />

如果您在視圖模型中使DateTime空,這將按預期工作:

[Required]
[DataType(DataType.Date)]
public DateTime? MyDate { get; set; }
[Required]
[DataType(DataType.Date)]
public Nullable<System.DateTime> MyDate { get; set; }

應該管用

暫無
暫無

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

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