如何设置在运行时RegularEx pression数据注解的常规前pression说法? [英] How can I set a RegularExpression data annotation's regular expression argument at runtime?

查看:122
本文介绍了如何设置在运行时RegularEx pression数据注解的常规前pression说法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们管理多个ASP.NET MVC客户端的网站,它们都使用一个数据注解像下面来验证客户电子邮件地址(我没有这里包括正则表达式,为便于阅读):

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, for readability):

[Required(ErrorMessage="Email is required")]
[RegularExpression(@"MYREGEX", ErrorMessage = "Email address is not valid")]
public string Email { get; set; }

我想要做的是集中该正前pression,因此,如果我们做出改变它,所有的网站立即把它捡起来,我们不必手动更改每之一。

What I would like to do is to centralise this regular expression, so that if we make a change to it, all of the sites immediately pick it up and we don't have to manually change it in each one.

问题是数据注解的正则表达式参数必须是恒定的,所以我不能分配(这是我的第一个想法),我从在运行配置文件或数据库中检索的值。

The problem is that the regex argument of the data annotation must be a constant, so I cannot assign a value I've retrieved from a config file or database at runtime (which was my first thought).

谁能帮我一个聪明的解决这个,如果不行的话,另一种方法,将努力实现同样的目标?还是这恰恰需要我们写一个专门定制验证属性,它会接受非恒定值?

Can anyone help me with a clever solution to this—or failing that, an alternative approach which will work to achieve the same goal? Or does this just require us to write a specialist custom validation attribute which will accept non-constant values?

推荐答案

最简单的方法是写一个自定义的 ValidationAttribute RegularEx $继承p $ pssionAttribute ,所以是这样的:

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")]

最后,要获得客户端验证工作,你只会增加你的Ap​​plication_Start方法下面在Global.asax内,告诉MVC使用普通的常规前pression验证这个验证:

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

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

这篇关于如何设置在运行时RegularEx pression数据注解的常规前pression说法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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