使用RegularExpression批注解析错误进行电子邮件地址验证

时间:2017-01-13 17:45:54

标签: c# regex asp.net-core-mvc

在我尝试使用RegularExpression批注来验证电子邮件地址时,我一直在加载创建页面时反向解析错误。为了获得包含的引号作为正则表达式的一部分,我尝试使用unicode,以便它可以在Visual Studio中工作。这也没有用。我也尝试了两个引号。

这是我想要使用的原始正则表达式:

  

(?:[!?一个-Z0-9#$%&安培;' + / = ^ _ {|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_ {|}〜 - ] +) |& #34;(:[\ x01- \ X08 \ X0B \ X0C \ x0e- \ X1F \ X21 \ x23- \ x5b \ x5d- \ 0x7F部分] | \ [\ x01- \ X09 \ X0B \ X0C \ x0e- \? 0x7F部分])"??)@(:( ?:一个-Z0-9)+ A-Z0-9 | [?(?::( 25 [0-5] | 2 [ 0-4] [0-9] | [01] [0-9] [0-9])){3}(?: 25 [0-5] |?2 [0-4] - [O- 9] | [01] [0-9] [0-9] | [A-Z0-9 - ] [A-Z0-9]:???(:[\ x01- \ X08 \ X0B \ X0C \ x0e- \ X1F \ x21- \ X5A \ x53- \ 0x7F部分] | \ [\ x01- \ X09 \ X0B \ X0C \ x0e- \ 0x7F部分])+)])

这是unicode我用以下内容替换了一些包含的引号:

  

\ u0022

[Required(ErrorMessage = "User e-mail required.")]
[Display(Name = "E-mail")]
[RegularExpression(@"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\u0022(?:[\x01 -\x08\x0b\x0c\x0e -\x1f\x21\x23 -\x5b\x5d -\x7f] |\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\u0022)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])", ErrorMessage = "Invalid format.")]
public string email { get; set; }

我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

You can go for following code:

[Required(ErrorMessage = "User e-mail required.")]
[Display(Name = "E-mail")]
[EmailAddress(ErrorMessage = "Invalid format.")]
public string email { get; set; }

OR

[Required(ErrorMessage = "User e-mail required.")]
[Display(Name = "E-mail")]
[RegularExpression(@"/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,4}$/",ErrorMessage = "Invalid format.")]
public string email { get; set; }

答案 1 :(得分:0)

<强> REGEXP

^[A-Za-z0-9\x{0430}-\x{044F}\x{0410}-\x{042F}\._-]+@(?:[A-Za-z0-9\x{0430}-\x{044F}\x{0410}-\x{042F}]{1,2}|[A-Za-z0-9\x{0430}-\x{044F}\x{0410}-\x{042F}](?:(?<!(\.\.))[A-Za-z0-9\x{0430}-\x{044F}\x{0410}-\x{042F}.-])+[A-Za-z0-9\x{0430}-\x{044F}\x{0410}-\x{042F}])\.[A-Za-z\x{0430}-\x{044F}\x{0410}-\x{042F}]{2,}$

<强> RESULT

potato@potato.com <== True
test@test.com <== True
test@test@test.com <== False
test@test <= False

请参阅: https://regex101.com/r/yL5M5m/1