如何将正则表达式数据注释与资源文件一起使用

发布于 2024-08-26 07:16:00 字数 454 浏览 8 评论 0原文

我目前正在使用 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 技术交流群。

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

发布评论

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

评论(2

早茶月光 2024-09-02 07:16:00

我建议您制作自己的 ValidationAttribute。这会将正则表达式以及错误消息保留在一处。

class PostcodeAttribute : RegularExpressionAttribute
{
    public PostcodeAttribute() : base("your regex")
    {
        this.ErrorMessage = "Postcode format invalid";
    }
}

I would suggest making your own ValidationAttribute. This will keep the regex in one place as well as the error message.

class PostcodeAttribute : RegularExpressionAttribute
{
    public PostcodeAttribute() : base("your regex")
    {
        this.ErrorMessage = "Postcode format invalid";
    }
}
冷…雨湿花 2024-09-02 07:16:00

无法对已接受的答案发表评论,因为我没有足够的代表。

这个接受的答案对我有用,但需要进行调整才能与不引人注目的 JavaScript 验证一起使用。需要此答案中的 IClientValidatable 位:https://stackoverflow.com/a/18041534/1714585

Can'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

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