2011-12-23 47 views
2

遇到我的電子郵件驗證代碼問題。我一直在收到我的函數沒有定義的錯誤。我爲java代碼創建了一個javascript文件,然後使用我的html中的onchange來觸發該函數。電子郵件驗證程序

<input type="text" id="email" name="email" onchange="check();" /> 

    function check() { 
email = document.getElementById("email").value; 
filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
if (filter.test(email.value)) 
    { 
    document.getElementById("email").style.border = "3px solid green"; 
    return true; 
    } 
else 
    { 
    document.getElementById("email").style.border = "3px solid red"; 
    return false; 
    } 
} 
+1

由於何時在電子郵件地址中出現了「+」號無效字符?爲什麼頂級域名不能有超過4個字符? – Quentin 2011-12-23 00:18:21

+0

+1。無需投票。 OP是問爲什麼得到甚至不是由正則表達式導致的JavaScript錯誤。 – 2011-12-23 00:21:32

+0

對不起,我仍然不習慣我必須發表問題的方式 – MunLau 2011-12-23 00:27:16

回答

3

把你的JavaScript在<script>標籤。

同時重命名變量名稱email因爲您的文本框已經在使用它了。

<input type="text" id="email" name="email" onchange="check();" /> 
<script type="text/javascript"> 
    function check() { 
     var email_x = document.getElementById("email").value; 
     filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
     if (filter.test(email.value)) { 
      document.getElementById("email").style.border = "3px solid green"; 
      return true; 
     } else { 
      document.getElementById("email").style.border = "3px solid red"; 
      return false; 
     } 
    } 
</script> 
1

電子郵件驗證並不總是像您的正則表達式一樣簡單。你看:

Validate email address in JavaScript?

一個更好的選擇是使用Verimail.js。這是一個簡單的腳本,爲你照顧它。使用Verimail.js,您可以執行以下操作:

var email = "[email protected]"; 
var verimail = new Comfirm.AlphaMail.Verimail(); 

verimail.verify(email, function(status, message, suggestion){ 
    if(status < 0){ 
     // Incorrect syntax! 
    }else{ 
     // Syntax looks great! 
    } 
}); 

上面的示例將命中'語法錯誤!'行。由於無效的TLD'cmo'。除此之外,它還會給出一個建議,您可以返回給您的用戶,在這種情況下,建議變量將包含'[email protected]',因爲'fabeook.cmo'看起來很像'facebook.com'。

希望這會有所幫助!

1

這裏是HTML輸入字段和按鈕字段代碼

<input input type="text" name="txtEmailId" id="txtEmailId" /> 
    <input type="submit" class="button" value="Suscribe" name="Suscribe" 
      onclick="javascript:ShowAlert()" /> 

現在添加以下功能到你的頁面的頁眉

<script type="text/javascript"> 
function ShowAlert() { 
    var email = document.getElementById('txtEmailId'); 
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
    if (!filter.test(email.value)) { 
     alert('Please provide a valid email address'); 
     email.focus; 
     return false; 
    } 
    else { 
     alert("Thanks for your intrest in us, Now you 
     will be able to receive monthly updates from us."); 
     document.getElementById('txtEmailId').value = ""; 
    } 
} 
</script> 

在這裏,你可以找到關於此Email Validation in JavaScript

文章
0

如果您具體瞭解域,您可以使用此代碼進行電子郵件驗證,以防止匿名電子郵件域。

(^([a-zA-Z]{1,20}[-_.]{0,1}[a-zA-Z0-9]{1,20})(\@gmail\.com|\@yahoo\.com|\@hotmail\.com)$) 

您也可以添加其他域。