1.案例
?
1.1 Html form表單內容
<form class="cForm" id="cForm" method="post" action=""> <p> <label for="user">用戶名</label> <input id="user" name="user" required minlength="3"> </p> <p> <label for="password">密碼</label> <input id="password" type="password" maxlength="12" name="password"> </p> <p> <input class="submit" type="submit" value="登錄"> </p> </form>
?
1.2 js代碼(進行表單自驗證)
<script>$().ready(function() {$("#cForm").validate({onsubmit:true,// 是否在提交是驗證onfocusout:false,// 是否在獲取焦點時驗證onkeyup :false,// 是否在敲擊鍵盤時驗證 rules: { //規則user: { //要對應相對應的input中的name屬性required: true},password: {required: true} }, messages:{ //驗證錯誤信息 user: {required: "請輸入用戶名"},password: {required: "請輸入密碼"} }, submitHandler: function(form) { //通過之后回調 //進行ajax傳值 $.ajax({url : "{:U('user/index')}",type : "post",dataType : "json",data: {user: $("#user").val(),password: $("#password").val() },success : function(msg) {//要執行的代碼 } }); }, invalidHandler: function(form, validator) {return false;} }); });</script>
?
1.3在控制器中對ajax傳遞的數據進行處理
? ? ?把ajax傳到控制器中的數據進行處理,返回結果。
?
1.4效果展示
?
?
?
2.validate的一些驗證參數
?
2.1使用表單自驗證可以通過導入js庫
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
可在官網進行下載
?
默認的校驗規則
序號 | 規則 | 描述 |
---|---|---|
1 | required:true | 必須輸入的字段。 |
2 | remote:"check.php" | 使用 ajax 方法調用 check.php 驗證輸入值。 |
3 | email:true | 必須輸入正確格式的電子郵件。 |
4 | url:true | 必須輸入正確格式的網址。 |
5 | date:true | 必須輸入正確格式的日期。日期校驗 ie6 出錯,慎用。 |
6 | dateISO:true | 必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22。只驗證格式,不驗證有效性。 |
7 | number:true | 必須輸入合法的數字(負數,小數)。 |
8 | digits:true | 必須輸入整數。 |
9 | creditcard: | 必須輸入合法的信用卡號。 |
10 | equalTo:"#field" | 輸入值必須和 #field 相同。 |
11 | accept: | 輸入擁有合法后綴名的字符串(上傳文件的后綴)。 |
12 | maxlength:5 | 輸入長度最多是 5 的字符串(漢字算一個字符)。 |
13 | minlength:10 | 輸入長度最小是 10 的字符串(漢字算一個字符)。 |
14 | rangelength:[5,10] | 輸入長度必須介于 5 和 10 之間的字符串(漢字算一個字符)。 |
15 | range:[5,10] | 輸入值必須介于 5 和 10 之間。 |
16 | max:5 | 輸入值不能大于 5。 |
17 | min:10 | 輸入值不能小于 10。 |
?
2.2將校驗規則寫到 js 代碼中
就像我上面寫的例子,直接把驗證規則和提示信息寫在js代碼中
$().ready(function() { // 在鍵盤按下并釋放及提交后驗證提交表單$("#signupForm").validate({rules: {firstname: "required",lastname: "required",username: {required: true,minlength: 2},password: {required: true,minlength: 5},confirm_password: {required: true,minlength: 5,equalTo: "#password"},email: {required: true,email: true},topic: {required: "#newsletter:checked",minlength: 2},agree: "required"},messages: {firstname: "請輸入您的名字",lastname: "請輸入您的姓氏",username: {required: "請輸入用戶名",minlength: "用戶名必需由兩個字母組成"},password: {required: "請輸入密碼",minlength: "密碼長度不能小于 5 個字母"},confirm_password: {required: "請輸入密碼",minlength: "密碼長度不能小于 5 個字母",equalTo: "兩次密碼輸入不一致"},email: "請輸入一個正確的郵箱",agree: "請接受我們的聲明",topic: "請選擇兩個主題"} });
?校驗規則中的名字必須與input中的name值對應
?
2.3常用方法及注意問題
?
2.3.1我們可以用其他方式替代默認的 submit
$().ready(function() {$("#signupForm").validate({submitHandler:function(form){ //表單提交后要執行的內容 form.submit();} }); });
使用ajax ? //跟我上面的ajax傳值差不多
$(".selector").validate({ submitHandler: function(form) { $(form).ajaxSubmit(); } })
?
2.3.2debug,只驗證不提交表單
$().ready(function() {$("#signupForm").validate({debug:true}); });
如果一個頁面中有多個表單都想設置成為 debug,則使用:
$.validator.setDefaults({debug: true })
?
2.3.3ignore:忽略某些元素不驗證
ignore: ".ignore"
?
2.3.4更改錯誤信息顯示的位置
errorPlacement:Callback
指明錯誤放置的位置,默認情況是:error.appendTo(element.parent());即把錯誤信息放在驗證的元素后面。
errorPlacement: function(error, element) { error.appendTo(element.parent()); }
?
2.3.5更改錯誤信息顯示的樣式
設置錯誤提示的樣式,可以增加圖標顯示,在該系統中已經建立了一個 validation.css,專門用于維護校驗文件的樣式。
input.error { border: 1px solid red; } label.error {background:url("./demo/images/unchecked.gif") no-repeat 0px 0px;padding-left: 16px;padding-bottom: 2px;font-weight: bold;color: #EA5200; } label.checked {background:url("./demo/images/checked.gif") no-repeat 0px 0px; }
?
2.3.6每個字段驗證通過執行函數
success: function(label) {// set as text for IElabel.html(" ").addClass("checked");//label.addClass("valid").text("Ok!") }
?
2.3.7驗證的觸發方式修改
觸發方式 | 類型 | 描述 | 默認值 |
---|---|---|---|
onsubmit | Boolean | 提交時驗證。設置為 false 就用其他方法去驗證。 | true |
onfocusout | Boolean | 失去焦點時驗證(不包括復選框/單選按鈕)。 | true |
onkeyup | Boolean | 在 keyup 時驗證。 | true |
onclick | Boolean | 在點擊復選框和單選按鈕時驗證。 | true |
focusInvalid | Boolean | 提交表單后,未通過驗證的表單(第一個或提交之前獲得焦點的未通過驗證的表單)會獲得焦點。 | true |
focusCleanup | Boolean | 如果是 true 那么當未通過驗證的元素獲得焦點時,移除錯誤提示。避免和 focusInvalid 一起用。 | false |
?重置表單 很實用
$().ready(function() {var validator = $("#signupForm").validate({submitHandler:function(form){alert("submitted"); form.submit();} });$("#reset").click(function() {validator.resetForm();});});
?
2.3.8異步驗證
使用 ajax 方式進行驗證,默認會提交當前驗證的值到遠程地址,如果需要提交其他的值,可以使用 data 選項。
remote: {url: "check-email.php", //后臺處理程序type: "post", //數據發送方式dataType: "json", //接受數據格式 data: { //要傳遞的數據username: function() {return $("#username").val();}} }
?
2.3.9添加自定義校驗
addMethod:name, method, message
自定義驗證方法
// 中文字兩個字節 jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {var length = value.length;for(var i = 0; i < value.length; i++){if(value.charCodeAt(i) > 127){length++;}}return this.optional(element) || ( length >= param[0] && length <= param[1] ); }, $.validator.format("請確保輸入的值在{0}-{1}個字節之間(一個中文字算2個字節)"));// 郵政編碼驗證 jQuery.validator.addMethod("isZipCode", function(value, element) { var tel = /^[0-9]{6}$/;return this.optional(element) || (tel.test(value)); }, "請正確填寫您的郵政編碼");
?
2.3.10radio 和 checkbox、select 的驗證
?
列舉一個demo統一驗證一下
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jQuery Validate radio(單選按鈕)、checkbox(復選按鈕)和 select(下拉框)</title><link rel="stylesheet" media="screen" href="http://static.runoob.com/assets/jquery-validation-1.14.0/demo/css/screen.css"> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script><style> .block { display: block; } form.cmxform label.error { display: none; } </style></head> <body><div id="main"><form class="cmxform" id="form1" method="get" action=""><fieldset><legend>通過 radio(單選按鈕)和 checkbox(復選按鈕)驗證表單</legend><fieldset><legend>性別</legend><label for="gender_male"><input type="radio" id="gender_male" value="m" name="gender" required>男性</label><label for="gender_female"><input type="radio" id="gender_female" value="f" name="gender">女性</label><label for="gender" class="error">請選擇您的性別。</label></fieldset><fieldset><legend>婚姻狀況</legend><label for="family_single"><input type="radio" id="family_single" value="s" name="family" required>單身</label><label for="family_married"><input type="radio" id="family_married" value="m" name="family">已婚</label><label for="family_other"><input type="radio" id="family_other" value="o" name="family">其他</label><label for="family" class="error">您選擇您的婚姻狀況。</label></fieldset><p><label for="agree">請同意我們的條款</label><input type="checkbox" class="checkbox" id="agree" name="agree" required><br><label for="agree" class="error block">請同意我們的條款!</label></p><fieldset><legend>垃圾郵件</legend><label for="spam_email"><input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" required minlength="2">垃圾郵件 - E-Mail</label><label for="spam_phone"><input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]">垃圾郵件 - Phone</label><label for="spam_mail"><input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]">垃圾郵件 - Mail</label><label for="spam[]" class="error">請選擇至少兩種類型的垃圾郵件。</label></fieldset><p><input class="submit" type="submit" value="提交"></p></fieldset> </form><form id="selecttest"><h2>一些關于 select 的測試</h2><p><label for="jungle">請選擇一個叢林名詞</label><br><select id="jungle" name="jungle" title="請選擇一個叢林名詞!" required><option value=""></option><option value="1">Buga</option><option value="2">Baga</option><option value="3">Oi</option></select></p><p><label for="fruit">請選擇至少兩種水果</label><br><select id="fruit" name="fruit" title="請選擇至少兩種水果!" required minlength="2" multiple="multiple"><option value="b">Banana</option><option value="a">Apple</option><option value="p">Peach</option><option value="t">Turtle</option></select></p><p><label for="vegetables">請選擇不超過兩種蔬菜</label><br><select id="vegetables" name="vegetables" title="請選擇不超過兩種蔬菜!" required maxlength="2" multiple="multiple"><option value="p">Potato</option><option value="t">Tomato</option><option value="s">Salad</option></select></p><p><label for="cars">請選擇至少兩種但不超過三種汽車</label><br><select id="cars" name="cars" title="請選擇至少兩種但不超過三種汽車!" required rangelength="[2,3]" multiple="multiple"><option value="m_sl">Mercedes SL</option><option value="o_c">Opel Corsa</option><option value="vw_p">VW Polo</option><option value="t_s">Titanic Skoda</option></select></p><p><input type="submit" value="Validate Select 測試"></p> </form></div></body> </html>
js代碼
<script> $.validator.setDefaults({submitHandler: function() {alert("submitted!");} });$(document).ready(function() {$("#form1").validate();$("#selecttest").validate(); }); </script>
?
大家有什么意見或者建議可以留言指導、批評