Which Data Annotation attribute creates this validation attribute?

六月ゝ 毕业季﹏ 提交于 2019-12-24 01:53:08

问题


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.

So, what data annotation will override the verbiage in the HTML attribute?

For instance, [Required(ErrorMessage="This field is required!")] will override the standard "The field {0} is required." message.


Failed attempts:

  1. [DataType(DataType.Date, ErrorMessage = "Must be a valid date.")] doesn't appear to do anything to client-side validation.

  2. [DisplayName("...")] changes the wildcard portion of the pattern, but obviously doesn't affect the pattern itself.


回答1:


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



来源:https://stackoverflow.com/questions/48349290/which-data-annotation-attribute-creates-this-validation-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!