Search code examples
c#asp.netasp.net-mvcdata-annotationsunobtrusive-validation

Date validation in ASP.NET MVC with DataAnnotations in ViewModel


I have a DateTime property in my page's ViewModel. I would like to know if there is a built-in way of checking that the user entered a valid date.

Here is what my current code looks like and as of now it is not automatically making sure the user enters a valid date (there is only required validation):

ViewModel property:

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

Razor MVC6 view:

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

Solution

  • If you make the DateTime nullable in your view model, this will work as you expect:

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