4

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" />
1
  • What do you mean by not automatically making sure the user enters a valid date? What is invalid: the format or is it out of range? What input are you entering and what happens then? What do you expect to happen? Commented Feb 3, 2016 at 17:28

2 Answers 2

8

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; }
Sign up to request clarification or add additional context in comments.

1 Comment

Does that work when applied on a string type ? (to ensure string has valid Date format)
5
[Required]
[DataType(DataType.Date)]
public Nullable<System.DateTime> MyDate { get; set; }

should work

1 Comment

same as what @RJCuthbertson said just a different way to write it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.