具有RegularExpression和ErrorMessage的Asp.Net MVC 4.0模型本地化 [英] Asp.Net MVC 4.0 Model Localization With RegularExpression and ErrorMessage

查看:90
本文介绍了具有RegularExpression和ErrorMessage的Asp.Net MVC 4.0模型本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建我的自定义RegularExpressionValidator来从资源文件中获取RegularExpression和ErrorMessage?

How to create my custom RegularExpressionValidator that gets the RegularExpression and ErrorMessage from Resource file?

 [RegularExpression(@"\d{5}(-\d{4})?",
          ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "regExpValforPostal_ErrorMessage")]
        public string PostalCode { get; set; }

推荐答案

资源文件名为Global:

The resource file name is Global :

Global.resx,Global.zh.resx,Global.fr-ca.resx

Global.resx, Global.zh.resx, Global.fr-ca.resx

 [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class LocalizedRegexAttribute : RegularExpressionAttribute
    {


        static LocalizedRegexAttribute()
        {
            // necessary to enable client side validation
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRegexAttribute), typeof(RegularExpressionAttributeAdapter));
        }

        public LocalizedRegexAttribute(string _RegularExpression, string _ErrorMessageResourceName, Type _ErrorMessageResourceType)
            : base(LoadRegex(_RegularExpression))
        {
            ErrorMessageResourceType = _ErrorMessageResourceType;
            ErrorMessageResourceName = _ErrorMessageResourceName;

        }

        private static string LoadRegex(string key)
        {
            var resourceManager = new ResourceManager(typeof(Water.Localization.Resources.Global));
            return resourceManager.GetString(key);
        }

在模型类中,您需要传递3个参数以及自定义数据 注释如下:

In your model class you need to pass 3 parameters with the custom data annotation as follows:

[LocalizedRegex("regExpValforPostal_ValidationExpression", "regExpValforPostal_ErrorMessage", typeof(Global))]
        public string PostalCode { get; set; }

这篇关于具有RegularExpression和ErrorMessage的Asp.Net MVC 4.0模型本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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