ASP.NET MVC 中的日期验证和 ViewModel 中的 DataAnnotations

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; }

应该可以