How can I set a RegularExpression data annotation's regular expression argument at runtime?

﹥>﹥吖頭↗ 提交于 2019-11-28 23:16:40
Ian Routledge

The easiest way is to write a custom ValidationAttribute that inherits from RegularExpressionAttribute, so something like:

public class EmailAttribute : RegularExpressionAttribute
    {
        public EmailAttribute()
            : base(GetRegex())
        { }

        private static string GetRegex()
        {
            // TODO: Go off and get your RegEx here
            return @"^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$";
        }
    }

That way, you still maintain use of the built in Regex validation but you can customise it. You'd just simply use it like:

[Email(ErrorMessage = "Please use a valid email address")]

Lastly, to get to client side validation to work, you would simply add the following in your Application_Start method within Global.asax, to tell MVC to use the normal regular expression validation for this validator:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));
Jeffrey Zhao

Do you really want to put the regex in database/config file, or do you just want to centralise them? If you just want to put the regex together, you can just define and use constants like

public class ValidationRegularExpressions {
    public const string Regex1 = "...";
    public const string Regex2 = "...";
}

Maybe you want to manage the regexes in external files, you can write a MSBuild task to do the replacement when you build for production.

If you REALLY want to change the validation regex at runtime, define your own ValidationAttribute, like

[RegexByKey("MyKey", ErrorMessage = "Email address is not valid")]
public string Email { get; set; }

It's just a piece of code to write:

public class RegexByKeyAttribute : ValidationAttribute {
    public RegexByKey(string key) {
        ...
    }

    // override some methods
    public override bool IsValid(object value) {
        ...
    }
}

Or even just:

public class RegexByKeyAttribute : RegularExpressionAttribute {
    public RegexByKey(string key) : base(LoadRegex(key)) { }

    // Be careful to cache the regex is this operation is expensive.
    private static string LoadRegex(string key) { ... }
}

Hope it's helpful: http://msdn.microsoft.com/en-us/library/cc668224.aspx

Why not just write you own ValidationAttribute?

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx

Then you can configure that thing to pull the regex from a registry setting... config file... database... etc... etc..

How to: Customize Data Field Validation in the Data Model Using Custom

Checkout ScotGu's [Email] attribute (Step 4: Creating a Custom [Email] Validation Attribute).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!