如何使用 RegularExpressionAttribute 返回失败正则表达式的字符串

我编写了有效的正则表达式,并返回错误消息供用户查看。在我的例子中,我正在验证一个字符串数组(电子邮件),我希望用户知道哪个字段失败了,而不仅仅是一条通用消息。有没有办法返回失败的字符串?


我可以编写自己的正则表达式处理系统,该系统将遍历字符串并返回正则表达式失败的那些。不过确实感觉有点不对劲,因为 .net 让我能够在我的模型上执行正则表达式。


如果它失败了,也许我弄错了模型正则表达式的功能。它失败。而且我只能知道哪个模型失败了,而不是哪个特定对象。


我查看了以下文档: https ://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.regularexpressionattribute?view=netframework-4.7.2


但是,我找不到任何返回对象的选项。但可能忽略了它。


    [Display(Name = "Admin Emails")]


    [RegularExpression(@"[a-z0-9!#$%&' * +/=?^ _`{|}~-]+(?:\.[a-z0- 

    9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0- 

    9](?:[a-z0-9-]*[a-z0-9])?",


    ErrorMessage = "Admin needs a valid email")]


    public List<string> AdminEmails { get; set; }

我的控制器只是检查模型


        if (!ModelState.IsValid)

        {

            return BadRequest(ModelState);

        }

我想要的是返回类似“admin@admin 需要是有效电子邮件”的错误消息


jeck猫
浏览 76回答 1
1回答

大话西游666

如果我们创建一个自定义属性,如下所示:&nbsp;public class EmailsCustomAttribute : ValidationAttribute&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public EmailsCustomAttribute(string pattern)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.Pattern = pattern;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public string Pattern { get; }&nbsp; &nbsp; &nbsp; &nbsp; protected override ValidationResult IsValid(object value, ValidationContext validationContext)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Regex regex = new Regex(Pattern);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<string> emails = value as List<string>;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string errorMessage = string.Empty;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (var item in emails)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!regex.IsMatch(item))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errorMessage += this.ErrorMessage.Replace("{0}", item);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ValidationResult validationResult = new ValidationResult(errorMessage);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return validationResult;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }并将其用作以下内容:public class TestModel&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; [EmailsCustom(@"[a-z0-9!#$%&' * +/=?^ _`{|}~-]+(?:\.[a-z0-&nbsp;&nbsp; &nbsp; 9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-&nbsp;&nbsp; &nbsp; 9](?:[a-z0-9-]*[a-z0-9])?", ErrorMessage = "{0} is invalid email")]&nbsp; &nbsp; &nbsp; &nbsp; public List<string> Emails { get; set; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP