简体   繁体   中英

MVC 5 - Default message and localization of DataAnnotations (email, Url etc)

I'm trying to find the keys of the default messages of the DataAnnotations in MVC 5.

For now, I found and used those with success:

FieldMustBeDate
FieldMustBeNumeric
PropertyValueInvalid
PropertyValueRequired

They are in a resource file: App_GlobalResources\\Messages

These lines were added in my global.asax:

ClientDataTypeModelValidatorProvider.ResourceClassKey = "Messages";
DefaultModelBinder.ResourceClassKey = "Messages";

Now, all this works perfectly, I have the messages configured in my resource file appear correctly.

But now I'm trying to find the property name of the resources for the other error messages, currently looking for these:

[Display(Name = "Website", ResourceType = (typeof(Properties.Resources)))]
[DataType(DataType.Url)]
[Url]
public string Website { get; set; }

[Display(Name = "Email", ResourceType = (typeof(Properties.Resources)))]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }

[Display(Name = "PhoneNumber", ResourceType = (typeof(Properties.Resources)))]
[Required]
[DataType(DataType.PhoneNumber)]
[Phone]
public string PhoneNumber { get; set; }

I tried some combination, like FieldMustBeEmail and FieldMustBeEmailAddress but it did not work. Are they available the same way as FieldMustBeDate or I will need to create my own DataAnnotations?

I checked the source code of MVC and the only way to do it is to set the ErrorMessageResourceType and the ErrorMessageResourceName of the attribute, then add it in my local resource file:

[Display(Name = "Email", ResourceType = (typeof(Properties.Resources)))]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessageResourceType = (typeof(App_GlobalResources.Messages)), ErrorMessageResourceName = "EmailAddressAttribute_Invalid")]
public string Email { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM