2013-01-21 80 views
0

我使用JavaScript驗證驗證了我的表單,因爲整個驗證工作正常,但電子郵件驗證無效。我的表單代碼如下javascript電子郵件驗證不起作用

<form method="post" action="contact.php" name="myForm" onsubmit="return validateForm()"> 

<h3>To know more contact us today.</h3> 

    <table> 
     <tr> 
      <td>Name: 
       <br /> 
       <input id="name" name="name" type="text" /> 
      </td> 
     </tr> 
     <tr> 
      <td>Contact No: 
       <br /> 
       <input id="contact" name="contact" type="text" /> 
      </td> 
     </tr> 
     <tr> 
      <td>Email: 
       <br /> 
       <input id="email" type="text" name="email" /> 
      </td> 
     </tr> 
     <tr> 
      <td>Address: 
       <br /> 
       <textarea cols="34" id="address" name="address" type="text"></textarea> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       <input type="submit" value="Submit" /> 
      </td> 
     </tr> 
    </table> 
</form> 

和我的javascript代碼如下

<script type="text/javascript"> 
     function validateEmail() { 

      var emailID = document.["myForm"]["email"].value; 
      atpos = emailID.indexOf("@"); 
      dotpos = emailID.lastIndexOf("."); 
      if (atpos < 1 || (dotpos - atpos < 2)) { 
       alert("Please enter correct email ID") 
       document.myForm.email.focus(); 
       return false; 
      } 
      return (true); 
     } 
     function validateForm() { 
      var x = document.forms["myForm"]["name"].value; 
      if (x == null || x == "") { 
       alert("First name must be filled"); 
       return false; 
      } 
      var x = document.forms["myForm"]["contact"].value; 
      if (x == null || x == "" || isNaN(document.myForm.contact.value) || document.myForm.contact.value.length != 10) { 
       alert("Contact Number Must be 10 Digits"); 
       return false; 
      } 
      var x = document.forms["myForm"]["email"].value; 
      if (x == null || x == "") { 
       alert("Email is must"); 
       return false; 
      } 
      else { 

       var ret = validateEmail(); 
       if (ret == false) { 
        return false; 
       } 
      } 
      var x = document.forms["myForm"]["address"].value; 
      if (x == null || x == "") { 
       alert("Address cannot be empty"); 
       return false; 
      } 
      return (true); 
     } 

    </script> 
+1

首先驗證邏輯不好。你有沒有聽說過regEx? –

+0

你會得到什麼樣的錯誤 –

+0

*有些人遇到問題時會想:「我知道,我會用正則表達式。」現在他們有兩個問題。* - [傑米Zawinski](http://en.wikiquote.org/wiki/Jamie_Zawinski) – Quentin

回答

4
var emailID = document.["myForm"]["email"].value; 
         ^^ 

語法錯誤。點符號或方括號符號。只選擇一個(每個屬性)。

我很驚訝Firebug/Chrome Developer Tools/Dragonfly/etc在測試時沒有給你一個明確的指針。