用于查找的电子邮件regex验证器替代方案

本文关键字:方案 验证 regex 查找 电子邮件 用于 | 更新日期: 2023-09-27 18:25:23

我的mvc应用程序上有以下代码:

[RegularExpression(@"^(?!'.)(""([^""'r'']|''[""'r''])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!'.)'.)*)(?<!'.)" + @"@[a-z0-9]['w'.-]*[a-z0-9]'.[a-z][a-z'.]*[a-z]$")]
public string Email { get; set; }

经过搜索,我发现这不起作用,因为有一个后备((?<!...))

有没有什么可以让我代替那个后备队员?提前感谢!

用于查找的电子邮件regex验证器替代方案

我建议您使用以下方法来验证电子邮件:

try {
    var addr = new System.Net.Mail.MailAddress(value);
    this.email = value;
}
catch {
    throw new Exception(); // or whatever
}

这是因为最好的(只有最好的结果,没有一个是完美的)电子邮件Regex看起来像这样:

/^(?!(?:(?:'x22?'x5C['x00-'x7E]'x22?)|(?:'x22?[^'x5C'x22]'x22?)){255,})(?!(?:(?:'x22?'x5C['x00-'x7E]'x22?)|(?:'x22?[^'x5C'x22]'x22?)){65,}@)(?:(?:['x21'x23-'x27'x2A'x2B'x2D'x2F-'x39'x3D'x3F'x5E-'x7E]+)|(?:'x22(?:['x01-'x08'x0B'x0C'x0E-'x1F'x21'x23-'x5B'x5D-'x7F]|(?:'x5C['x00-'x7F]))*'x22))(?:'.(?:(?:['x21'x23-'x27'x2A'x2B'x2D'x2F-'x39'x3D'x3F'x5E-'x7E]+)|(?:'x22(?:['x01-'x08'x0B'x0C'x0E-'x1F'x21'x23-'x5B'x5D-'x7F]|(?:'x5C['x00-'x7F]))*'x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*'.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:'[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:']]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:'.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))']))$/iD