Presuming we have a model like so:
public class TheViewModel
{
public string DateTime? Image_Date { get; set; }
}
And it is added to a Razor view like so:
Html.TextBoxFor(model => model.Image_Date)
Then the following is rendered in the browser:
<input data-val="true" data-val-date="The field Image_Date must be a date." id="Image_Date" name="Image_Date" type="text" value="" />
The attribute data-val-date
is what I'm interested in. It's plainly being injected in by MVC's "unobtrusive" jQuery validation integration.
For instance, [Required(ErrorMessage="This field is required!")]
will override the standard "The field {0} is required." message.
Failed attempts:
[DataType(DataType.Date, ErrorMessage = "Must be a valid date.")]
doesn't appear to do anything to client-side validation.
[DisplayName("...")]
changes the wildcard portion of the pattern, but obviously doesn't affect the pattern itself.
The data-val-date
attribute is added by the framework because the property is type of DateTime?
. Its the GetUnobtrusiveValidationAttributes()
method of the HtmlHelper
class which actually generates all the data-val-*
attributes.
Note that [DataType(DataType.Date, "...")]
is an attribute used by the EditorFor()
method to add the type="date"
attribute which in turn generates the browsers HTML-5 datepicker (if its supported by the browser) and is not related with client side validation.
The default error messages are defined in Resource files, and you can create you own to override the defaults.
Create a (say) MyResources.resx
in the App_GlobalResources
folder (you may need to create this folder) and add the following FieldMustBeDate
key and your message (the default message is shown below)
FieldMustBeDate : The field {0} must be a date
and add the following in the Application_Start()
of Global.asax
ClientDataTypeModelValidatorProvider.ResourceClassKey = "MyResources";
DefaultModelBinder.ResourceClassKey = "MyResources";
Note you can also override the default error message for the [Required]
attribute using the PropertyValueRequired
key