如何在运行时设置正则表达式数据注释的正则表达式参数?

发布于 2024-12-20 02:53:09 字数 482 浏览 2 评论 0原文

我们管理几个 ASP.NET MVC 客户端网站,它们都使用如下所示的数据注释来验证客户电子邮件地址(为了便于阅读,我没有在此处包含正则表达式):

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

我想做的是集中此常规表达式,这样如果我们对其进行更改,所有站点都会立即拾取它,而我们不必在每个站点中手动更改它。

问题是数据注释的正则表达式参数必须是常量,因此我无法分配在运行时从配置文件或数据库检索到的值(这是我的第一个想法)。

任何人都可以帮助我找到一个巧妙的解决方案吗?或者如果失败了,可以采用替代方法来实现相同的目标吗?或者这是否只需要我们编写一个接受非常量值的专业自定义验证属性?

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

奶气 2024-12-27 02:53:09

最简单的方法是编写一个继承自 RegularExpressionAttribute 的自定义 ValidationAttribute,例如:

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})?$";
        }
    }

这样,您仍然可以使用内置的正则表达式验证,但可以自定义它。您只需简单地使用它即可:

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

最后,要使客户端验证正常工作,您只需在 Global.asax 内的 Application_Start 方法中添加以下内容即可告诉 MVC 为此验证器使用普通的正则表达式验证:

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

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));
月光色 2024-12-27 02:53:09

查看 ScotGu 的 [Email] 属性(步骤 4:创建自定义 [Email] 验证属性)。

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

别把无礼当个性 2024-12-27 02:53:09

您真的想将正则表达式放入数据库/配置文件中,还是只想集中它们?如果您只想将正则表达式放在一起,您可以定义和使用常量,例如

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

也许您想管理外部文件中的正则表达式,您可以编写一个 MSBuild 任务来在构建生产。

如果您确实想在运行时更改验证正则表达式,请定义您自己的 ValidationAttribute,就像

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

这只是要编写的一段代码:

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

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

或者甚至只是:

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) { ... }
}

希望它有帮助: http://msdn.microsoft.com/en-us/library/cc668224.aspx

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

蓝戈者 2024-12-27 02:53:09

为什么不直接编写自己的 ValidationAttribute 呢?

http://msdn.microsoft.com/en-us /library/system.componentmodel.dataannotations.validationattribute.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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文