2014-03-05 95 views
0

我爲我的頁面創建了一個小型jQuery表單驗證,但我不知道問題出在哪裏。jquery表單驗證無法正常工作

我使用event.preventDefault();停止提交表格,如果這些字段爲空且#phone不是數字。

但數字提示也不起作用。 :(

這裏是我的jQuery代碼:

$(document).ready(function(){ 

    $("#form").submit(function(e) { 
     var f_name = $('#f_name').val(); 
     var l_name = $('#l_name').val(); 
     var phone = $('#phone').val(); 



     if(f_name == '') { 
      alert('First Name feild is empty!'); 
      var tf_name = false; 
     } else { 
      var tf_name = true; 
     } 
     if(l_name == '') { 
      alert('Last Name feild is empty!'); 
      var tl_name = false; 
     } else { 
      var tl_name = true; 
     } 

     if(phone == '') { 
      alert('Phone feild is empty!'); 
      var tphone = false; 
     } 
     if(phone) { 
      $("#phone").keydown(function (e) { 
       // Allow: backspace, delete, tab, escape, enter and . 
       if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 || 
        // Allow: Ctrl+A 
        (e.keyCode == 65 && e.ctrlKey === true) || 
        // Allow: home, end, left, right 
        (e.keyCode >= 35 && e.keyCode <= 39)) { 
         // let it happen, don't do anything 
         var tphone = true; 
         alert("You jast allow to use numbers!") 
         return; 
       } 
       // Ensure that it is a number and stop the keypress 
       if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { 
        e.preventDefault(); 
       } 
      }); 
     } 

     e.preventDefault(); 
    }); 

}); 

這裏是我的HTML代碼,我用:

<form action="userC.php" method="post" id="form"> 
    <p>First Name: <input type="text" name="f_name" id="f_name" /></p> 
    <p>Last Name: <input type="text" name="l_name" id="l_name" /></p> 
    <p>Phone Number: <input type="text" name="phone" id="phone" /></p> 
    <p><input type="submit" name="submit" /></p> 
</form> 
+0

不工作?多數民衆贊成在很好:)然後解決問題 –

+0

看起來你正在檢查哪些鍵和什麼不是瘋狂。你爲什麼不在用戶點擊提交時檢查它是否是一個數字? –

回答

2

我會建議使用jQuery的驗證功能,這是很容易。和有用的

這裏是我的代碼:

function FormValidate() { 
validator=$("#form").validate({ 
    rules: { 
     "f_name":{ 
     required:true, 
     minlength: 3 
     },    
     "l_name":{ 
     required:true, 
     minlength: 3 
     }, 
     "phone":{ 
     required:true, 
     number: true 
     } 
    }, 
    messages: { 
     "f_name":{ 
     required: "First name is required." 
     }, 
     "l_name":{ 
     required: "Last name is required." 
     }, 
     "phone":{ 
     required:"Phone is required.", 
     number: "Please provide a valid phone number." 
     }  
    } 
    }); 
    x=validator.form(); 
    return x; 
} 

$(document).ready(function(){ 
    $("#form").submit(function(e) { 
    var chk = FormValidate(); 
if(!chk){ 
    return false; 
} 
}); 

});