Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Globally localize validation

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...