如何将正则表达式数据注释与资源文件一起使用
我目前正在使用 MVC 1.0 和 .NET 3.5。我正在使用 DataAnnotations 来验证我的模型。我正在尝试添加使用正则表达式来验证邮政编码。我已将我的正则表达式存储在资源文件中,因为许多模型都会使用它,当我尝试以下操作时:
[RegularExpression(Resources.RegexPostcode, ErrorMessage="Postcode format invalid")]
public string Postcode { get; set; }
构建时出现以下错误:
属性参数必须是 常量表达式、typeof 表达式 或数组创建表达式 属性参数类型。
有没有办法使用资源文件中的值作为正则表达式,或者我需要将实际的正则表达式字符串输入到每个具有邮政编码的模型中?
谢谢
I am currently using MVC 1.0 and .NET 3.5. I am using DataAnnotations to validate my model. I'm trying to add use the RegularExpression to validate a Postcode. I have stored my Regex in the resource file as many models will use it, when I try the following:
[RegularExpression(Resources.RegexPostcode, ErrorMessage="Postcode format invalid")]
public string Postcode { get; set; }
I get the following error when I build:
An attribute argument must be a
constant expression, typeof expression
or array creation expression of an
attribute parameter type.
Is there any way to use values from a Resource file as the regex or will I need to enter the actual regex string into every model that has a postcode?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议您制作自己的 ValidationAttribute。这会将正则表达式以及错误消息保留在一处。
I would suggest making your own ValidationAttribute. This will keep the regex in one place as well as the error message.
无法对已接受的答案发表评论,因为我没有足够的代表。
这个接受的答案对我有用,但需要进行调整才能与不引人注目的 JavaScript 验证一起使用。需要此答案中的
IClientValidatable
位:https://stackoverflow.com/a/18041534/1714585Can't leave a comment on the accepted answer as I don't have enough rep.
This accepted answer worked for me, but needed a tweak to work with the unobtrusive javascript validation. Needed the
IClientValidatable
bits from this answer: https://stackoverflow.com/a/18041534/1714585