Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" />
like image 610
Blake Rivell Avatar asked Oct 29 '25 01:10

Blake Rivell


1 Answers

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; }
like image 89
RJ Cuthbertson Avatar answered Oct 30 '25 18:10

RJ Cuthbertson