跨数据注释/属性共享正则表达式的方法
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C# 中,您只需要一个转义码(双引号)...如果您使用逐字字符串文字:
我总是使用
@" 编写正则表达式。 .."
字符串 - 避免了许多令人头疼的问题。In C# there is only one escape code you need (double-quote)... if you use verbatim string literals:
I always write regex with
@"..."
strings - avoids many headaches.显然,在 .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."
您可以创建自定义验证属性 像这样作为代理,它将从您的资源文件加载正则表达式。
You could create a custom validation attribute like this as a proxy which would load the regular expressions from your resource file.