全球本地化验证 [英] Globally localize validation

查看:36
本文介绍了全球本地化验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 System.ComponeneModel.DataAnnotations 属性,例如Required 和 StringLength.是否可以全局本地化其错误消息?

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

我知道我能做到

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

但是在我使用 required 属性的任何地方都这样做是很疯狂的.我也想避免这样的事情:

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)

推荐答案

AFAIK 您需要自定义属性或指定 ErrorMessageResourceName 和 ErrorMessageResourceType 属性.还有另一种可能性这里详述:

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

在中创建一个全局资源类App_GlobalResources,并设置DefaultModelBinder.ResourceClassKey 到此类的名称(例如,如果您制作了Messages.resx",则设置ResourceClassKey 到消息").

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").

您可以覆盖两个字符串在 MVC 2 中:

There are two strings you can override in MVC 2:

  • 字符串值PropertyValueInvalid"在以下情况下使用用户输入的数据不是与数据类型兼容(对于例如,输入abc"整数字段).默认消息因为这是:值 '{0}' 不是对 {1} 有效."

  • 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}."

字符串值PropertyValueRequired"在以下情况下使用用户没有输入任何数据不可为空的字段(对于例如,整数字段).这默认消息是:一个值是必需的."

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."

重要的是要注意在第二种情况下,如果你有这DataAnnotationsModelValidatorProvider在您的验证器提供商列表中(默认情况下),那么你永远不会看到第二条消息.此提供程序看到非可选字段并添加一个隐含的 [必需]归因于他们,使他们的消息将与其他消息一致具有显式 [必需] 的字段属性,并确保你得到需要的客户端验证字段.

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.

这篇关于全球本地化验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆