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

前端 未结 4 1461
长发绾君心
长发绾君心 2020-12-15 06:08

We manage several ASP.NET MVC client web sites, which all use a data annotation like the following to validate customer email addresses (I haven\'t included the regex here,

4条回答
  •  情深已故
    2020-12-15 06:47

    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

提交回复
热议问题