validate+jquery+ajax表單驗證

1.案例php

 

1.1 Html form表單內容css

<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代碼(進行表單自驗證)html

<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傳遞的數據進行處理jquery

     把ajax傳到控制器中的數據進行處理,返回結果。git

 

1.4效果展現ajax

  

 

 

 

2.validate的一些驗證參數json

 

2.1使用表單自驗證能夠經過導入js庫app

<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 &nbsp; as text for IE
    label.html("&nbsp;").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>

 

你們有什麼意見或者建議能夠留言指導、批評

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息