JavaScript(js)如何验证一个字符串是否是有效的电子邮箱地址呢,正则表达式又应该如何写呢?
3 个回答
-
在JavaScript(js)中,使用正则表达式来验证字符串是否是有效电子邮箱地址是最好的方法,如下是一个适用于匹配unicode编码的字符邮箱地址的正则表达式:
const re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
示例js代码如下:
function validateEmail(email) { const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function validate() { const $result = $("#result"); const email = $("#email").val(); $result.text(""); if (validateEmail(email)) { $result.text(email + "有效 :)"); $result.css("color", "green"); } else { $result.text(email + "无效 :("); $result.css("color", "red"); } return false; } $("#email").on("input", validate);
HTML代码如下:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for=email>请输入邮箱地址:</label> <input id="email"> <h2 id="result"></h2>
-
一种符合RFC822标准的电子邮箱格式验证函数,包含正则表达式验证,代码如下:
function checkEmail(emailAddress) { var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; var sQuotedPair = '\\x5c[\\x00-\\x7f]'; var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d'; var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22'; var sDomain_ref = sAtom; var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')'; var sWord = '(' + sAtom + '|' + sQuotedString + ')'; var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*'; var sLocalPart = sWord + '(\\x2e' + sWord + ')*'; var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec var sValidEmail = '^' + sAddrSpec + '$'; // as whole string var reValidEmail = new RegExp(sValidEmail); return reValidEmail.test(emailAddress); }