【问题标题】:Can I use my RegularExpression attribute instead of the DataAnnotations one?我可以使用我的 RegularExpression 属性而不是 DataAnnotations 属性吗?
【发布时间】:2023-12-08 03:06:01
【问题描述】:

我正在尝试使用可重用的正则表达式类并与 MVC 中的 DataAnnotations 一起使用。比如:

[RegularExpressionAttribute1(typeof(MyRegex))] 

这会编译,但如果属性不匹配,则不会引发错误。

一切都符合标准

[RegularExpression(@"^\s*\d+(\.\d{1,2})?\s*$")]

【问题讨论】:

    标签: .net regex data-annotations


    【解决方案1】:

    您可以创建自定义验证属性来重用正则表达式。对于电子邮件验证,您可以执行以下操作:

    using System.ComponentModel.DataAnnotations;
    
    public class EmailAttribute : RegularExpressionAttribute
    {
        public EmailAttribute()
            : base(@"(?i)^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$") { }
    }
    

    【讨论】:

      最近更新 更多