jquery中validate與form外掛程式提交的方式小結,jqueryvalidate

來源:互聯網
上載者:User

jquery中validate與form外掛程式提交的方式小結,jqueryvalidate

概述:本篇主要討論jquery.validate結合jquery.form實現對錶單的驗證和提交方案。

方式一:是通過jquery.validate的submitHandler選項,即當表單通過驗證時執行回呼函數。在這個回呼函數中通過jquery.form來提交表單;

方式二:是通過jquery.form的beforeSubmit,即在提交表單前執行的回呼函數,這個函數如果返回true,則提交表單,如果返回false,則終止提交表單。根據jquery.validate外掛程式的valid()方法,就可以通過jquery.form提交表單時來對錶單進行驗證。

方式三:是通過jquery.validate驗證表單的validate方法。這個方法的好處是對錶單驗證的控制更加自由

執行個體:下面通過三個執行個體分別闡述上面的三種方式

載入CSS樣式檔案

複製代碼 代碼如下:<link rel="stylesheet" type="text/css" media="screen" href="style.css" />

CSS樣式檔案內容

input{ height:25px; line-height:25px; padding-left:4px;}span.checked{ padding: 0px 5px 0px 25px; margin-left: 10px; margin-top: 0px; margin-bottom: 3px; height: 25px; line-height:25px; font-size: 12px; white-space: nowrap; text-align: left; color: #E6594E; background: url("images/acion2.png") no-repeat 3px; /* #FCEAE8 */}span.unchecked{ padding: 0px 5px 0px 25px; margin-left: 10px; margin-top: 0px; margin-bottom: 3px; height: 23px; line-height:23px; font-size: 12px; border: 1px solid #E6594E; white-space: nowrap; text-align: left; color: #E6594E; background: #FCEAE8 url("images/acion.png") no-repeat 3px;}

載入javascript檔案

<script language="JavaScript" type="text/JavaScript" src="js/jQuery1.6.2.js"></script><script language="JavaScript" type="text/JavaScript" src="js/jquery.form.js"></script><script language="JavaScript" type="text/JavaScript" src="js/jquery.validate.js"></script><script language="JavaScript" type="text/JavaScript" src="js/localization/messages_tw.js"></script>

HTML內容

<body><span id="result"></span><form id='commentForm'> <fieldset> <legend>jquery.validate+jquery.form提交的三種方式</legend>  <p>   <label for='cusername'>姓名</label><em>*</em>   <input id='cusername' name='username' size='25' />  </p>  <p>   <label for='cemail'>電子郵件</label><em>*</em>   <input id='cemail' name='email' size='25' />  </p>  <p>   <input class='submit' type='submit' value='提交'>  </p> </fieldset></form></body>

jquery.validate+jquery.form提交方式1的javascript內容

<script language="javascript">function showResponse(responseText,statusText) { if(statusText=='success'){  $("#result").html(responseText); }}$(document).ready(function(){ $('#commentForm').validate({  focusCleanup:true,focusInvalid:false,  errorClass: "unchecked",  validClass: "checked",  errorElement: "span",  submitHandler:function(form){   $(form).ajaxSubmit({    type:"post",    url:"test_save.php?time="+ (new Date()).getTime(),    //beforeSubmit: showRequest,    success: showResponse   });  },  errorPlacement:function(error,element){   var s=element.parent().find("span[htmlFor='" + element.attr("id") + "']");   if(s!=null){    s.remove();   }   error.appendTo(element.parent());  },  success: function(label) {   //label.addClass("valid").text("Ok!")   label.removeClass("unchecked").addClass("checked");  },  rules:{   username:{required:true,minlength:3},   email:{    required:true   }  } });});</script>

jquery.validate+jquery.form提交方式2的javascript內容

<script language="javascript">function showResponse(responseText,statusText) { if(statusText=='success'){  $("#result").html(responseText); }}function showRequest(formData,jqForm,options){ return $("#commentForm").valid();}$(document).ready(function(){ $('#commentForm').submit(function(){  $(this).ajaxSubmit({   type:"post",   url:"test_save.php?time="+ (new Date()).getTime(),   beforeSubmit:showRequest,   success:showResponse  });  return false; //此處必須返回false,阻止常規的form提交 }); $('#commentForm').validate({  focusCleanup:true,focusInvalid:false,  errorClass: "unchecked",  validClass: "checked",  errorElement: "span",  errorPlacement:function(error,element){   var s=element.parent().find("span[htmlFor='" + element.attr("id") + "']");   if(s!=null){    s.remove();   }   error.appendTo(element.parent());  },  success: function(label) {   //label.addClass("valid").text("Ok!")   label.removeClass("unchecked").addClass("checked");  },  rules:{   username:{required:true,minlength:3},   email:{    required:true   }  } });});</script>

jquery.validate+jquery.form提交方式3的javascript內容

<script language="javascript"> var options={  focusCleanup:true,focusInvalid:false,  errorClass: "unchecked",  validClass: "checked",  errorElement: "span",  errorPlacement:function(error,element){   var s=element.parent().find("span[htmlFor='" + element.attr("id") + "']");   if(s!=null){    s.remove();   }   error.appendTo(element.parent());  },  success: function(label) {   //label.addClass("valid").text("Ok!")   label.removeClass("unchecked").addClass("checked");  },  rules:{   username:{required:true,minlength:3},   email:{    required:true   }  } };function showResponse(responseText,statusText) { if(statusText=='success'){  $("#result").html(responseText); }}function showRequest(formData,jqForm,options){ return $("#commentForm").valid();}$(document).ready(function(){ validator=$('#commentForm').validate(options); $("#reset").click(function(){  validator.resetForm(); }); $("button").click(function(){  validator.form(); }); $('#commentForm').submit(function(){  $(this).ajaxSubmit({   type:"post",   url:"test_save.php?time="+ (new Date()).getTime(),   beforeSubmit:showRequest,   success:showResponse  });  return false; //此處必須返回false,阻止常規的form提交 });});</script>

DEMO源碼:下載

一些問題

1、其實這個問題在昨天晚上寫這篇文章的時候就有發現,即我在HTML檔案頭使用<!DOCTYPE html>時,輸入框及錯誤資訊的樣式似乎有些問題。不過今天發現問題並非這麼簡單,在使用<!DOCTYPE html>時,針對“姓名”這個輸入框來說——只須達到三個字元就認為通過驗證——在輸入第一個字元、第二個字元時,錯誤顯示正常,輸入第三個字元時,錯誤顯示消失,並顯示一個表示驗證通過的“逗號”圖片。到目前為止,一切似乎都很正常,但如果在繼續輸入字元,比如輸入第四個字元、第五個字元......問題出現了。如所示:

不使用<!DOCTYPE html>,而使用<html>時沒有這樣的問題,一切正常。不過,現在的問題是,為什麼加上<!DOCTYPE html>會產生這樣的問題?而且,做為前端來說,加上<!DOCTYPE html>是必須的。

這個問題處理的比較糾結,這裡羅列一下處理的過程。並且在最後給一個解決方案

首先,是因為昨天在查看錯誤提示資訊,關注一下插入錯誤資訊的代碼。我在errorPlacement中增加了一句:alert(element.parent().html());

errorPlacement:function(error,element){ alert(element.parent().html()); var s=element.parent().find("span[htmlFor='" + element.attr("id") + "']"); if(s!=null){  s.remove(); } error.appendTo(element.parent());},

輸入第一個字元時,得到如所示

輸入三個字元,驗證成功後,得到如所示:

繼續輸入更多字元,得到如所示

這就說明了以下幾個問題:

1、不管驗證失敗還是成功,都會調用errorPlacement:function(...)

2、s.remove()沒有起作用。

由於在寫這篇文章時使用的是<html>而不是<!DOCTYPE html>,彈出的內容是htmlFor="cusername",而不是for="cusername",如所示:

因此,上面的代碼中寫成如下的方式

 var s=element.parent().find("span[htmlFor='" + element.attr("id") + "']"); if(s!=null){  s.remove(); }

然而在<!DOCTYPE html>下,無法根據htmlFor找到<span generated="true" htmlFor="cusername"></span>,因此這裡應該把htmlFor改成for,即

errorPlacement:function(error,element){ alert(element.parent().html()); var s=element.parent().find("span[for='" + element.attr("id") + "']"); if(s!=null){  s.remove(); } error.appendTo(element.parent());},

問題似乎解決了。但上面提到,不管驗證成功或失敗,都會調用errorPlacement:function(...),那可以在這裡判斷有沒有錯誤,如果有錯誤,則顯示。防止已經驗證成功的情況下仍會調用。這樣就不會尋找span的for屬性值是否為當前控制項的name名稱了(例子中是for="cusername")。改進的代碼如下:

errorPlacement:function(error,element){ if(error.html()!=''){  error.appendTo(element.parent()); }},

雖然解決問題,但是在chrome、firefox下仍有問題。瞭解這個問題的現象,可以用firefox或chrome測試一下——焦點離開輸入框後,無法驗證,只有點擊“提交”按鈕後才可以驗證——這個問題的解決方案目前還沒有深入下去。但是有解決的辦法是,將上面的jquery1.6.2換成jquery1.3.2或jquery1.4(其它的jquery版本未測試,可能是低於jquery1.6.2的版本都可以)即可解決這個問題。

建議:

1、使用jquery1.3.2版本,這樣可以節省很多時間來解決相容方面的問題。

更多:

本例子中的jquery.validate,解決了remote遠程驗證只返回true or false的局限。可以傳回碼及出錯的提示資訊,更好的人性化需求。使用方法就在這介紹一下

增加以下函數

function GetRemoteInfo(postUrl,data){ var remote = {  type: "POST",  async: false,  url: postUrl,  dataType: "xml",  data: data,  dataFilter: function(dataXML) {   var result = new Object();   result.Result = jQuery(dataXML).find("Result").text();   result.Msg = jQuery(dataXML).find("Msg").text();   //alert(result.Result);   if (result.Result == "-1") {    result.Result = false;    return result;   }else{    result.Result = result.Result == "1" ? true : false;    return result;   }  } }; return remote;}

$(document).ready(function(){ var dataInfo ={email:function(){return $("#cemail").val();}}; var remoteInfo = GetRemoteInfo('check-email.php?time='+(new Date()).getTime(),dataInfo); $('#commentForm').validate({  rules:{   username:{    required:true,    minlength:3   },   email:{    required:true,    remote:remoteInfo   }  } }); ....});

check-email.php返回的內容為xml格式,格式如下

<?phpheader("Content-Type:text/xml");echo '<?'.'xml version="1.0" encoding="utf-8"'.' ?>';?><AjaxClass><Msg>使用者名稱格式不正確,使用者名稱必須包含testa,請重新輸入!</Msg><Result>0</Result></AjaxClass>

result值為0,返回的是false,表示驗證失敗;result值為1,返回的是true,表示驗證成功

您可能感興趣的文章:
  • jQuery.Validate 使用筆記(jQuery Validation範例 )
  • jquery.validate使用攻略 第一部
  • jquery.validate使用攻略 第三部
  • jquery.validate使用攻略 第五步 正則驗證
  • $.format,jquery.format 使用說明
  • IE中jquery.form中ajax提交沒反應解決方案分享
  • jQuery.Validate驗證庫的使用介紹
  • Jquery.Form 非同步提交表單的簡單一實例
  • jquery.form.js用法之清空form的方法
  • 基於Bootstrap+jQuery.validate實現Form表單驗證
  • jquery.form.js實現將form提交轉為ajax方式提交的方法
  • jquery.validate使用時遇到的問題
  • jquery.validate提示錯誤資訊位置方法

聯繫我們

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