jQuery – jQuery Validate Ajax

來源:互聯網
上載者:User

標籤:app   lin   min   back   inline   invalid   cors   ota   ash   

【LJ?Dragon】魚對水說你看不到我的眼淚,因為我在水裡。水說我能感覺到你的眼淚,因為你在我心裡。
【LJ?Dragon】You’re more than a shadow, I’ve just to believe.
【LJ?Dragon】A true friend is some one who reaches for your hand and touches your heart.

jquery.validate ajax方式驗證
<script type="text/javascript">    $(function () {        $("#form1").validate({            rules: {                pwd: {                    required: true,                    remote: {                        url: "@Url.Action("ValidatePwd", "UserInfo")",                        type: "post",                        dataType: "json",                        data: {                            pwd: function () {                                return $("#pwd").val();    //這個是取要驗證的密碼                            }                        },                        dataFilter: function (data) {    //判斷控制器返回的內容                            if (data == "true") {                                return true;                            }                            else {                                return false;                            }                        }                    }                },                password: {                    required: true,                    rangelength: [6, 16]                },                confirm_password: {                    required: true,                    rangelength: [6, 16],                    equalTo: "#password"                }            },            messages: {                pwd: {                    required: "請填寫原始密碼!",                    remote: "原始密碼不正確,請重新填寫!"    //這個地方如果不寫的話,是內建的提示內容,加上就是這個內容。                },                password: {                    required: "請填寫新密碼",                    minlength: jQuery.format("登入名稱長度在6-12位之間!")                },                confirm_password: {                    required: "請填寫確認密碼!",                    minlength: "密碼需由6-16個字元(數字、字母、底線)組成!",                    equalTo: "兩次輸入密碼不一致!"                }            },            onfocus: true,                onkeyup: false,    //這個地方要注意,修改去控制器驗證的事件。            onsubmit: false        });

 

2.案例
<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>

 

2.1 使用
<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>

菜鳥教程:http://www.runoob.com/jquery/jquery-plugin-validate.html

$().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值對應

 

3. 常用方法及注意問題3.1我們可以用其他方式替代預設的 submit
$().ready(function() { $("#signupForm").validate({        submitHandler:function(form){  //表單提交後要執行的內容            form.submit();        }        });});
使用ajax
$(".selector").validate({      submitHandler: function(form)    {            $(form).ajaxSubmit();        }   })
3.2debug,只驗證不提交表單
$().ready(function() { $("#signupForm").validate({        debug:true    });});
如果一個頁面中有多個表單都想設定成為 debug,則使用:
$.validator.setDefaults({   debug: true})
3.3ignore:忽略某些元素不驗證
ignore: ".ignore"
3.4更改錯誤資訊顯示的位置
errorPlacement:Callback
指明錯誤放置的位置,預設情況是:error.appendTo(element.parent());即把錯誤資訊放在驗證的元素後面。
errorPlacement: function(error, element) {      error.appendTo(element.parent());  }
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;}
3.6每個欄位驗證通過執行函數
success: function(label) {    // set   as text for IE    label.html(" ").addClass("checked");    //label.addClass("valid").text("Ok!")}
3.7驗證的觸發方式修改
重設表單 很實用
 
$().ready(function() { var validator = $("#signupForm").validate({        submitHandler:function(form){            alert("submitted");               form.submit();        }        });    $("#reset").click(function() {        validator.resetForm();    });});
3.8非同步驗證
remote: {    url: "check-email.php",     //幕後處理程式    type: "post",               //資料發送方式    dataType: "json",           //接受資料格式       data: {                     //要傳遞的資料        username: function() {            return $("#username").val();        }    }}
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));}, "請正確填寫您的郵遞區號");
3.10radio 和 checkbox、select 的驗證
<!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>
 
<script>$.validator.setDefaults({    submitHandler: function() {        alert("submitted!");    }});$(document).ready(function() {    $("#form1").validate();    $("#selecttest").validate();});</script>

 

Reference:

【….】http://www.cnblogs.com/jingmin/p/6294982.html

 
 
 
 
 
 

jQuery – jQuery Validate Ajax

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.