2012-12-06 78 views
1

可能重複:
Validate email address in Javascript?電子郵件驗證用JavaScript

這是我的第一篇文章,我有一個小問題。我試圖驗證表單上的電子郵件地址,但沒有運氣。我在互聯網上發現了這個片段,但它似乎沒有工作。我現在使用Javascript來驗證它。我通常不使用JS,所以任何幫助,將不勝感激。

<script type="text/javascript"> 
    function ValidateEmail(inputText) 
    { 
     var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; 
     if(inputText.value.match(mailformat)) 
     { 
      document.forms.emailform(); 
      return true; 
     } 
     else 
     { 
      alert("You have entered an invalid email address!"); 
      document.forms.emailform(); 
      return false; 
     } 
    } 

<?php 
    $addemail .= ' 

     <form method="post" action="cart2.php" name="emailform" onsubmit="return validateEmail"> 
     '; 
    $addemail .= ' 
      E-mail Address: <input type="text" name="email" value="'.$row6['email'].'" size="19" /><input type="hidden" name="cartid" value="'.$cart.'" />'; 
     if ($emailerror != '') 
      { 
       $addemail .= '<img src="images/email_error.png" width="16" height="16" hspace="4" alt="E-mail Error" />'; 
      } 
     $addemail .= ' 
      <input type="image" name="Add E-mail Address" alt="Add E-mail Address" src="images/addemail.gif" style="vertical-align:middle" /> 
     </form> 
    '; 
    if ($row6['email'] == '') 
     { 
      $emailpresent = 0; 
     } 
    else 
     { 
      $emailpresent = 1; 
     } 
} 
     $addemail .= ' 
       </td> 
      </tr> 
     '; 
} 

?> 
+0

「不工作」是什麼意思?你的表單沒有提交(當你調用'document.forms.emailForm()'時,可能有錯誤),這是無效的)? –

+0

這個正則表達式試圖禁止一些完全有效和真實的電子郵件地址(其中有'+ +的地址和''博物館'和'info'頂級域名(TLD))。 – Quentin

+0

HTML5定義了一個新的輸入'type =「email」'。它有'pattern'屬性,你可以在其中指定一個正則表達式。更多詳情[here](http://www.w3.org/TR/html-markup/input.email.html) –

回答

0
onsubmit="return validateEmail()" 

您必須調用它validateEmail後加括號,否則會假設你試圖返回的方法。

4

看看它如何能在Javascript來完成這個例子:

<html> 

<head> 
<script type="text/javascript"> 
<!-- 
function validateEmail() { 
    var emailText = document.getElementById('email').value; 
    var pattern = /^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/; 
    if (pattern.test(emailText)) { 
     return true; 
    } else { 
     alert('Bad email address: ' + emailText); 
     return false; 
    } 
} 

window.onload = function() { 
    document.getElementById('email_form').onsubmit = validateEmail; 
} 
</script> 

</head> 
<body> 

<form id="email_form"> 
<input type="text" id="email"> 
<input type="submit"> 
</form> 

</body> 
</html> 


編輯:

如果你確信你的網頁的用戶正在使用HTML5兼容的瀏覽器,你可以使用下面的整潔的例子來達到同樣的目的:

<!DOCTYPE html> 

<html> 
    <body> 
     <form> 
      <input type="email" pattern="^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*@[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$"> 
      <input type="submit"> 
     </form> 
    </body> 
</html>