ErrorMessage property

296 views Asked by At

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>
1

There are 1 answers

0
Lin On

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.

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

MVC will generate it to below code:

<input class="text-box single-line" data-val="true" data-val-date="The field Scheduled Date/Time must be a date." data-val-required=":-(" id="Scheduled_Date" name="Scheduled_Date" type="datetime" value=""/>
<span class="field-validation-valid" data-valmsg-for="Scheduled_Date" data-valmsg-replace="true"/>

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 :

[Required(ErrorMessage = ":-("), 
DataType(DataType.DateTime), 
Display(Name = "Scheduled Date/Time")]
DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Scheduled_Date { get; set; }