Globally localize validation

2019-01-18 01:20发布

问题:

I'm using System.ComponeneModel.DataAnnotations attributes such as Required and StringLength. Is it possible to localize its error messages globally?

I know I can do this

[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))]

But doing this everywhere I use required attribute would be just insane. Also I'd like to avoid stuff like:

public class LocalizedRequiredAttribute : RequiredAttribute {
    public LocalizedRequiredAttribute()
        : base() {
        ErrorMessageResourceName = "Required";
        ErrorMessageResourceType = typeof(Resources.Validation);
    }
}

(but if there isn't any other way, I'll settle for this)

回答1:

AFAIK you need either a custom attribute or specify the ErrorMessageResourceName and ErrorMessageResourceType properties. There is another possibility detailed here:

Create a global resource class in App_GlobalResources, and set DefaultModelBinder.ResourceClassKey to the name of this class (for example, if you made "Messages.resx", then set ResourceClassKey to "Messages").

There are two strings you can override in MVC 2:

  • The string value for "PropertyValueInvalid" is used when the data the user entered isn't compatible with the data type (for example, typing in "abc" for an integer field). The default message for this is: "The value '{0}' is not valid for {1}."

  • The string value for "PropertyValueRequired" is used when the user did not enter any data for a field which is not nullable (for example, an integer field). The default message for this is: "A value is required."

It's important to note in the second case that, if you have the DataAnnotationsModelValidatorProvider in your validator providers list (which it is by default), then you will never see this second message. This provider sees non-optional fields and adds an implied [Required] attribute to them so that their messages will be consistent with other fields with explicit [Required] attributes and to ensure that you get client-side validation for required fields.



回答2:

For MVC3 see DataAnnotationsResources. It's "RequiredAttribute_ValidationError" and more. You may solve it by installing .NET Framework language pack(s).

See also