2016-07-10 56 views
0

所以我有這個註冊表單,我如何驗證這一點,因爲每次我提交和事件時,沒有數據會在每次按下按鈕時被添加到數據庫中。這是到目前爲止我的代碼:你如何驗證jquery/ajax表單?

<form id="signupform" class="form" method="post" action="#"> 
    <div class="input-prepend" ><span class="add-on"><i class="glyphicon glyphicon-user"></i></span> 
     <label for="name">Your Full Name</label> 
      <input type="text" id="name" name="name" placeholder="your full name" size="40"> 
    </div> 

    <br /> 

    <div class="input-prepend"><span class="add-on"><i class="glyphicon glyphicon-envelope"></i></span> 
      <label for="email">Your Email</label> 
       <input type="email" id="email" name="email" placeholder="[email protected]" size="40" style="color:black;" class="validate" required> 
    </div> 

    <br /> 

    <button type="submit" class="btn btn-large" name="action"> Sign Up!</button> 
</form> 

,這就是我對我的jQuery代碼:

$(document).ready(function(){ 
     jQuery("#signupform").on("submit",function(e){ 
      e.preventDefault(); 
      var name = jQuery("#name").val(); 
      var email = jQuery("#email").val(); 
      var fd = new FormData(); 
      fd.append("name",name); 
      fd.append("email",email); 
      jQuery.ajax({ 
       type: 'POST', 
       url: 'signup.php', 
       data: fd, 
       processData: false, 
       contentType: false 
      }) 
      jQuery('#signupform')[0].reset();  

     }); 


    }); 
+2

然後你有2個問題。無論您在瀏覽器中驗證什麼,客戶端都不會信任任何東西,並且您必須在服務器上進行驗證,否則您將整個站點置於風險中 – charlietfl

回答

0
$(document).ready(function(){ 
     jQuery("#signupform").on("submit",function(e){ 
      e.preventDefault(); 
      var name = jQuery("#name").val(); 
      var email = jQuery("#email").val(); 

      if (!nome || !email || !email.match(/[email protected]+[.].+/)) 
      { 
       alert("complete the form before submit"); 
       return; 
      } 

      var fd = new FormData(); 
      fd.append("name",name); 
      fd.append("email",email); 
      jQuery.ajax({ 
       type: 'POST', 
       url: 'signup.php', 
       data: fd, 
       processData: false, 
       contentType: false 
      }) 
      jQuery('#signupform')[0].reset();  

     }); 


    }); 
+0

感謝!我如何檢查電子郵件是否有效?就好像他們只是在沒有@ – tash517

+0

的地方使用正則表達式的隨機單詞,在if中添加這個條件:'!email.match(/[email protected]+[.].+/)' – lmcarreiro