2016-07-08 146 views
-2

好的,所以我需要一個帶有Javascript的電子郵件驗證程序。所以,我使用了這個StackOverflow answer的代碼。問題涉及在之後放置一個空間您的電子郵件地址。如果我輸入[email protected],則不會發生任何錯誤。如果我輸入[email protected],請注意最後添加的空間,電子郵件地址被證明無效。人們犯錯誤和增加的空間不應該認爲電子郵件地址無效。我該如何解決這個問題?電子郵件正則表達式允許驗證空格

function validateEmail(email) { 
 
    var re = /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[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() { 
 
    $("#result").text(""); 
 
    var email = $("#email").val(); 
 
    if (validateEmail(email)) { 
 
    $("#result").text(email + " is valid :)"); 
 
    $("#result").css("color", "green"); 
 
    } else { 
 
    $("#result").text(email + " is not valid :("); 
 
    $("#result").css("color", "red"); 
 
    } 
 
    return false; 
 
} 
 

 
$("form").bind("submit", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<form> 
 
    <p>Enter an email address:</p> 
 
    <input id='email'> 
 
    <button type='submit' id='validate'>Validate!</button> 
 
</form> 
 

 
<h2 id='result'></h2>

+0

'變種的電子郵件= $( 「#電子郵件」)VAL()修剪();'就足夠。請參見[答案](http://stackoverflow.com/a/3000900/5781248) –

回答

0

你需要添加\s*。字符\s將只匹配單個空格字符和*0與之匹敵 - 第n個倍。

您會希望在此之後放置此文件/^(...{2,})) ***insert \s* here *** $/;

下面是完整的更新行:

function validateEmail(email) { 
    var re = /^\s*(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[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,}))\s*$/; 

function validateEmail(email) { 
 
    var re = /^\s*(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[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,}))\s*$/; 
 
    return re.test(email); 
 
} 
 

 
function validate() { 
 
    $("#result").text(""); 
 
    var email = $("#email").val(); 
 
    if (validateEmail(email)) { 
 
    $("#result").text(email + " is valid :)"); 
 
    $("#result").css("color", "green"); 
 
    } else { 
 
    $("#result").text(email + " is not valid :("); 
 
    $("#result").css("color", "red"); 
 
    } 
 
    return false; 
 
} 
 

 
$("form").bind("submit", validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<form> 
 
    <p>Enter an email address:</p> 
 
    <input id='email'> 
 
    <button type='submit' id='validate'>Validate!</button> 
 
</form> 
 

 
<h2 id='result'></h2>

相關問題