跨数据注释/属性共享正则表达式的方法

发布于 2024-08-14 02:58:48 字数 333 浏览 9 评论 0原文

我正在使用 System.ComponentModel.DataAnnotations 命名空间,以期在我的 ASP.NET MVC 应用程序上进行一些验证。

我已经遇到了正则表达式注释的问题。

因为这些注释是属性,所以它们需要常量表达式。

好的,我可以使用一个充满正则表达式字符串常量的类。

问题是我不想用 C# 解析器所需的转义字符污染我的正则表达式。我的偏好是将正则表达式存储在资源文件中。

问题是我无法在数据注释中使用这些字符串资源,因为它们不是常量!

有什么办法解决这个问题吗?

如果不是,这似乎是使用属性进行验证的一个重大限制。

I am playing around with the System.ComponentModel.DataAnnotations namespace, with a view to getting some validation going on my ASP.NET MVC application.

I have already hit an issue with the RegularExpression annotation.

Because these annotations are attributes they require constant expressions.

OK, I can use a class filled with regex string constants.

The problem with that is I don't want to pollute my regex with escape characters required for the C# parser. My preference is to store the regex in a resources file.

The problem is I cant use those string resources in my data annotations, because they are not constants!

Is there any solution to this?

If not, this seems a significant limitation of using attributes for validation.

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

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

发布评论

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

评论(3

沧笙踏歌 2024-08-21 02:58:48

在 C# 中,您只需要一个转义码(双引号)...如果您使用逐字字符串文字:

@"like \this\ note \slash here does nothing only quote "" needs doubling
you can even use newline";

总是使用 @" 编写正则表达式。 .." 字符串 - 避免了许多令人头疼的问题。

In C# there is only one escape code you need (double-quote)... if you use verbatim string literals:

@"like \this\ note \slash here does nothing only quote "" needs doubling
you can even use newline";

I always write regex with @"..." strings - avoids many headaches.

鹤仙姿 2024-08-21 02:58:48

显然,在 .NET 4 中,DataAnnotations 属性有一些替代,这些属性采用 功能< string> 在其构造函数中被描述为“允许访问验证资源的函数”。

Apparently in .NET 4 there are overrides for the DataAnnotations attribubtes that take a Func< string> in their constructor described as "The function that enables access to validation resources."

时光礼记 2024-08-21 02:58:48

您可以创建自定义验证属性 像这样作为代理,它将从您的资源文件加载正则表达式。

You could create a custom validation attribute like this as a proxy which would load the regular expressions from your resource file.

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