Asp.Net MVC 4.0 Model Localization With RegularExp

2019-07-29 15:25发布

问题:

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; }

回答1:

The resource file name is Global :

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);
        }

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; }


回答2:

if your resources file called Validations.he.resx and inside it you have both 'RegexExpression' and 'ErrorMessage' you should use this:

UPDATE #1: Option 2 added

  • Option 1:

    public class LocalizedRegexAttribute :RegularExpressionAttribute
    {
        public LocalizedRegexAttribute () : base(Validations.RegexExpression)
        {
    
        }
    
        public override string FormatErrorMessage(string name)
        {
            return base.FormatErrorMessage(ValidationStrings.ErrorMessage);
        }
    }
    
  • Option 2:

public class EmailAddressAttribute :ValidationAttribute {
public EmailAddressAttribute()
{

}

public override bool IsValid(object value)
{
    Regex regex = new Regex(Validations.RegexExpression);
    return regex.IsMatch(value.ToString());
}

public override string FormatErrorMessage(string name)
{
    return base.FormatErrorMessage(ValidationStrings.ErrorMessage);
} }

than you will use it like this:

[LocalizedRegexAttribute]
public string PostalCode { get; set; }