此實例需要驗證的內容:中文姓名、手機號、地址,驗證方法分享給大家供大家參考,具體內容如下:
<form class="txzl"> <p>請填寫資料:</p> <label>姓名:<input type="text" name="username" id="name" /></label> <label>電話:<input type="text" name="userphone" maxlength="11" id="phone" /></label> <label>地址:<input type="text" name="useraddress" id="address" /></label> <div class="info_tj">提交</div> </form>
js:
// 手機號只能輸入數字 $("#phone").bind("keyup", function () { $(this).val($(this).val().replace(/[\D]/g, "")); }); // 地址只能輸入中文英文數字 $("#address").bind("keyup", function(){ $(this).val($(this).val().replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, "")); }); // 點擊提交領獎按鈕 驗證規則 $('.info_tj').on('click', function () { formValidate(); }); // 驗證中文名稱 function isChinaName(name) { var pattern = /^[\u4E00-\u9FA5]{1,6}$/; return pattern.test(name); } //test()方法 判斷字符串中是否匹配到正則表達式內容,返回的是boolean值 ( true / false ) // 驗證規則函數 function formValidate() { var str = ''; // 判斷名稱 if ($.trim($('#name').val()).length == 0) { str += '姓名沒有輸入\n'; $('#name').focus(); } else { if (isChinaName($.trim($('#name').val())) == false) { str += '請輸入中文姓名\n'; $('#name').focus(); } } // 判斷手機號碼 if ($.trim($('#phone').val()).length == 0) { str += '手機號沒有輸入\n'; $('#phone').focus(); } else { if ($.trim($('#phone').val()).length < 11) { str += '手機號位數不正確\n'; $('#phone').focus(); } } // 驗證地址 if ($.trim($('#address').val()).length == 0) { str += '地址沒有輸入\n'; $('#address').focus(); } // 如果沒有錯誤則提交 if (str != '') { alert(str); return false; } else { console.log($('#name').val()) console.log($('#phone').val()) console.log($('#address').val()) } };