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

前端 未结 4 1463
长发绾君心
长发绾君心 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 07:01

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

提交回复
热议问题