jQuery的validate驗證外掛程式使用方法

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   使用   

(1)預設校正規則
(1)required:true 必輸欄位
(2)remote:"check.php" 使用ajax方法調用check.php驗證輸入值
(3)email:true 必須輸入正確格式的電子郵件
(4)url:true 必須輸入正確格式的網址
(5)date:true 必須輸入正確格式的日期
(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)預設的提示
messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
dateDE: "Bitte geben Sie ein g眉ltiges Datum ein.",
number: "Please enter a valid number.",
numberDE: "Bitte geben Sie eine Nummer ein.",
digits: "Please enter only digits",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: $.validator.format("Please enter no more than {0} characters."),
minlength: $.validator.format("Please enter at least {0} characters."),
rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
range: $.validator.format("Please enter a value between {0} and {1}."),
max: $.validator.format("Please enter a value less than or equal to {0}."),
min: $.validator.format("Please enter a value greater than or equal to {0}.")
},

(3)

自訂校正規則:

   $(document).ready(function(){                    $("#empForm").validate({              //驗證規則              rules:{                   realname:"required",                  username:{                      required:true,                      rangelength:[5,8]                  },                  psw:{                      required:true,                      rangelength:[6,12]                  },                  psw2:{                      required:true,                      equalTo:"#psw"                  },                  gender:{                      required:true                  },                  age:{                      digits:true,                      range:[10,15]                  },                  edu:{                      required:true                  },                  birthday:{                      required:true,                      date:true                  },                  checkbox1:{                      required:true                  },                  email:{                      email:true                  },                  cart:{                      cardCheck:"2"                  }              },                            //提示資訊              messages:{                  realname:"真實姓名不可為空",                  username:{                      required:"登入名稱不可為空",                      rangelength:"登入名稱長度為5到8之間"                  },                  psw:{                      required:"密碼不可為空",                      rangelength:"密碼長度為6到12之間"                  },                  psw2:{                      required:"確認密碼不可為空",                      equalTo:"兩次密碼輸入不一致"                  },                  gender:{                      required:"請選擇性別"                  },                  age:{                      digits:"輸入的必須是數字",                      range:"年齡必須在10-15之間"                  },                  edu:{                      required:"學曆必須選擇一項"                  },                  birthday:{                      required:"生日必須填寫",                      date:"日期格式為1900/01/01"                  },                  checkbox1:{                      required:"興趣愛好必須選"                  },                  email:{                      email:"郵箱格式不正確"                  }              },                            //驗證成功後進行的操作              success: function(label) {                  label.html(" ").addClass("right");//引號裡的是& nbsp;              }                                      });      });          //自訂校正規則          /*          * addMethod:          *      第一個參數是:驗證方法的名稱,會在rules和messages中用到          *      第二個參數是:回調方法          *                  第一個參數value:組件中的值          *                  第二個參數element:組件對象          *                  第三個參數:表示錯誤提示資訊,如果messages中也寫了錯誤提示資訊,那麼會覆蓋掉這個資訊          */          $.validator.addMethod("cardCheck",function(value,element,params){  //          alert("value--->"+value);  是文字框輸入的值  //          alert("element--->"+element);  組件對象  //          alert("params--->"+params);   預設值2  在rules中  cart:{cardCheck:"2"}              if(value!=null){                  if(value.length>=15&&value.length<=18)                      return true;              }else{                  return false;              }          },"錯誤提示資訊");  

 

驗證成功後的樣式:

 

/* 驗證成功後的樣式 */      label.right{margin-left:4px; padding-left:20px; background:url(checked.gif) no-repeat 2px 0;vertical-align: middle;}  

 

 

[html] view plaincopyprint? 
<html>      <head>          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />          <title>jQuery validation plug-in - main demo</title>          <link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />          <script type="text/javascript" src="js/jquery-1.4.2.js"></script>          <script type="text/javascript" src="js/jquery.validate.js"></script>            <script type="text/javascript">      //這裡添加  </script>    </head>  <body>      <p>員工資訊錄入</p>  <form name="empForm" id="empForm" method="post" action="test.html">          <table border=1>              <tr>                  <td>真實姓名(不可為空 ,沒有其他要求)</td>                  <td><input type="text" id="realname" name="realname" />                  </td>              </tr>              <tr>                  <td>登入名稱(登入名稱不可為空,長度應該在5-8之間,可以包含中文字元(一個漢字算一個字元)):</td>                  <td><input type="text" id="username" name="username" /></td>              </tr>               <tr>                 <td>密碼(不可為空,長度6-12字元或數字,不能包含中文字元):</td>                <td><input type="password" id="psw"  name="psw" style="width:120px" /></td>              </tr              <tr>                 <td>重複密碼密碼(不可為空,長度6-12字元或數字,不能包含中文字元):</td>                <td><input type="password" id="psw2" name="psw2" style="width:120px" /></td>              </tr>                                  <!--                  label style="display: none" for="gender" class="error"您的性別必須選擇一個label                    * label:是jquery中顯示錯誤資訊的標籤                    * class="error"屬性工作表示存放錯誤資訊的                    * for屬性工作表示該標籤的唯一標識,jquery驗證架構運行時,先以for="gender"為條件尋找lable標籤                         * 如果找到,直接使用                         * 如果沒有找到,建立一個新的標籤                              label style="display: none" for="gender" class="error"                                                底層代碼                        errorClass: "error",                        errorElement: "label",                                                                  label = $("<" + this.settings.errorElement + "/>")   ----$("<label/>")                      .attr({"for":  this.idOrName(element), generated: true})                      .addClass(this.settings.errorClass)                      .text(message || "");                                        label=<label for="name屬性的值" class="error"  >xxxxx</label>                         -->                                          <tr>                  <td>性別(必選其一)</td>                  <td>                      <input  type="radio" id="gender_male" value="m" name="gender"/>男                      <input  type="radio" id="gender_female" value="f" name="gender"/>女                      <!-- 寫這個標籤是為了防止預設將提示資訊緊挨著‘男‘顯示 -->                      <label style="display: none" for="gender"  class="error">您的性別必須選擇一個</label>                  </td>                                </tr>              <tr>                  <td>年齡(必填26-50):</td>                  <td><input type="text" id="age" name="age" /></td>              </tr>                            <tr>                 <td>你的學曆:</td>                <td> <select name="edu" id="edu">                        <option value="">--請選擇你的學曆--</option>                        <option value="a">專科</option>                        <option value="b">本科</option>                        <option value="c">研究生</option>                        <option value="e">碩士</option>                        <option value="d">博士</option>                    </select>                </td>              </tr>                            <tr>                 <td>出生日期(1982/09/21):</td>                 <td><input type="text" id="birthday"  name="birthday" style="width:120px" value="" /></td>              </tr>                           <tr>                 <td>興趣愛好:</td>                <td colspan="2">                     <input type="checkbox" name="checkbox1" id="qq1"/>乒乓球                     <input type="checkbox" name="checkbox1" id="qq2" value="1" />羽毛球                     <input type="checkbox" name="checkbox1" id="qq3" value="2" />上網                     <input type="checkbox" name="checkbox1" id="qq4" value="3" />旅遊                     <input type="checkbox" name="checkbox1" id="qq5" value="4" />購物                     <!-- 寫這個標籤是為了防止預設將提示資訊緊挨著‘乒乓球‘顯示 -->                    <label  style="display: none" for="checkbox1" class="error">您的興趣愛好,至少選擇一個</label>                </td>              </tr>               <tr>                     <td align="left">電子郵箱:</td>                    <td><input type="text" id="email" style="width:120px" name="email" /></td>               </tr>                <tr>                     <td align="left">身份證(15-18):</td>                    <td><input type="text" id="cart"  style="width:120px" name="cart" /></td>                </tr>              <tr>                  <td></td>                  <td></td>                  <td><input type="submit"  name="firstname"  id="firstname" value="儲存"></td>              </tr>          </table>    </form>  </body>  </html>  

 

注意事項:

1.匯入validate.js檔案

注意:

*validate.js必須在jQuery.js檔案之後匯入,因為驗證架構裡需要用到jQuery.js中定義的方法

*如果先匯入jQuery.js再匯入validate.js   再次匯入jQuery.js也不行。因為驗證架構裡會將某些方法進行擴充,而後又一次匯入jQuery.js會將擴充的方法覆蓋。

 

2.指定要驗證的組件

注意:

*將驗證的代碼寫在$(document).ready(function(){.....})或$(function(){.....})的function中,因為必須等到所有的DOM結構繪製完畢後才能執行,否則會報錯,找不到元素。

 

3.在要被驗證的組件上加class屬性

注意:

使用class="{}"的方式,必須引入包:jquery.metadata.js可以使用如下的方法,修改提示內容:
class="{required:true,minlength:5,messages:{required:‘請輸入內容‘}}"在使用equalTo關鍵字時,後面的內容必須加上引號,如下代碼:
class="{required:true,minlength:5,equalTo:‘#password‘}"

*在組件上加class屬性有兩種方式:

1.class="required email"  多種規則用空格分隔

2.class="{required:true,email:true}"   json格式

當然也可以混用class="{required:true} email"

 

進行單獨的提示訊息覆蓋:

[javascript] view plaincopyprint?
姓名<input type="text" name="userName" class="{required:true,minlength:3,messages:{required:‘姓名必填‘,minlength:‘不能少於3個字‘}}">  
[javascript] view plaincopyprint?
<script type="text/javascript">      //自訂驗證提示訊息      jQuery.extend(jQuery.validator.messages, {          required: "請填寫本欄位",          remote: "驗證失敗",          email: "請輸入正確的電子郵件",          url: "請輸入正確的網址",          date: "請輸入正確的日期",          dateISO: "請輸入正確的日期 (ISO).",          number: "請輸入正確的數字",          digits: "請輸入正確的整數",          creditcard: "請輸入正確的信用卡號",          equalTo: "請再次輸入相同的值",          accept: "請輸入指定的尾碼名的字串",          maxlength: jQuery.validator.format("允許的最大長度為 {0} 個字元"),          minlength: jQuery.validator.format("允許的最小長度為 {0} 個字元"),          rangelength: jQuery.validator.format("允許的長度為{0}和{1}之間"),          range: jQuery.validator.format("請輸入介於 {0} 和 {1} 之間的值"),          max: jQuery.validator.format("請輸入一個最大為 {0} 的值"),          min: jQuery.validator.format("請輸入一個最小為 {0} 的值")      });      $(document).ready(function(){          $("form").validate();      });  </script>  [javascript] view plaincopyprint? <style type="text/css">      /* class=error的label組件  */      label.error{          margin-left: 10px;          color: red;      }  </style>  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.