简体   繁体   English

电子邮件的Javascript正则表达式,允许在电子邮件中使用“ \\”

[英]Javascript regex for email allowing '\' in email

I have a regex for my email: 我的电子邮件有一个正则表达式:

const EMAIL = /^(([^<>()\[\].,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

I want to validate below email as true: 我想验证以下电子邮件为真:

Fred\ Bloggs@example.com true
Joe.\\Blow@example.com true
""test\\blah""@example.com true

Below email as false: ""test\\blah""@example.com 在电子邮件下方为false:“” test \\ blah“” @ example.com

currently, I'm not able to do this validation please help 目前,我无法执行此验证,请帮助

 function validateEmail(email) { var re = /(([^<>()\\[\\].,;:\\s@\\"]+(\\.[^<>()\\[\\]\\.,;:\\s@\\"]+)*)|(\\".+\\"))@(([^<>()[\\]\\.,;:\\s@\\"]+\\.)+[^<>()[\\]\\.,;:\\s@\\"]{2,})$/i; return re.test(String(email).toLowerCase()); } var test_email1 ='""test\\blah""@example.com"'; alert(validateEmail(test_email1)); var test_email2 ='Fred\\ Bloggs@example.com'; alert(validateEmail(test_email2)); var test_email3 ='Joe.\\\\Blow@example.com'; alert(validateEmail(test_email3)); var test_email4 ='""test\\\\blah""@example.com'; alert(validateEmail(test_email4)); 

Here is the function from Omid's answer using a regex that meets RFC 2822 . 这是Omid使用符合RFC 2822的正则表达式回答的功能。

function validateEmail(email) {
    var re = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[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])+)\])/;
    return re.test(String(email).toLowerCase());
}

console.log(validateEmail('Fred\ Bloggs@example.com')); // logs true
console.log(validateEmail('Joe.\\Blow@example.com')); // logs true
console.log(validateEmail('""test\\blah""@example.com')); // logs true

You'll notice this function doesn't return false on the case you'd like to fail. 您会注意到,如果您要失败,此函数不会返回false

The only way to really test an email address is to send an email to it -- don't rely on regex to verify email addresses because your regex will never be perfect. 真正测试电子邮件地址的唯一方法是向其发送电子邮件-不要依靠正则表达式来验证电子邮件地址,因为您的正则表达式永远不会完美。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM