I have a view model with a property like Listing 1, and a view like Listing 2. The ErrorMessage when the DataType is incorrect format is not displayed. Instead, "The field Scheduled Date/Time must be a date." is displayed when the field lost focus. This default error message seems to be generated by the @Html.EditorFor as the client side validation script. How do I set it so that it use my ErrorMessage speified in my ViewModel? Thanks.
Listing 1:
[Required(ErrorMessage = ":-("),
DataType(DataType.DateTime, ErrorMessage = "Not a valid date/time"),
Display(Name = "Scheduled Date/Time")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Scheduled_Date { get; set; }
Listing 2:
<p>
<span class="editor-label">Schedule Date/Time:</span>
@Html.EditorFor(model => model.Scheduled_Date)
@Html.ValidationMessageFor(model => model.Scheduled_Date)
</p>
DataType attributes can't be used to validate user input. In your case MVC should generate data-val-* attributes mapping the HTML5 message to the user's request.
Like the code you provided.
MVC will generate it to below code:
Users will see "The field Scheduled Date/Time must be a date." if they enter some invalid input into the field, it's not "Not a valid data/time".
However, I suggest you use Jquery Datepicker, it doesn't even allow user to enter any text, but a valid date.
Then your viewModel should looks like :