搜尋
首頁web前端js教程jQuery Validate表單驗證深入學習_jquery

The previous article introduced the basic knowledge of jQuery Validate form validation. For details, please refer to "JQuery Validate Form Validation Getting Started Learning" , Today’s This article provides an in-depth study of jQuery Validate form validation. The following is the entire content of the article:

1. Use other methods to replace the default SUBMIT

$().ready(function() {
 $("#signupForm").validate({
    submitHandler:function(form){
      alert("submitted");  
      form.submit();
    }  
  });
});

Use ajax method

 $(".selector").validate({   
 submitHandler: function(form) 
  {   
   $(form).ajaxSubmit();   
  } 
 }) 

You can set the default value of validate, which is written as follows:

 $.validator.setDefaults({
 submitHandler: function(form) { alert("submitted!");form.submit(); }
});

If you want to submit a form, you need to use form.submit() instead of $(form).submit().
2. Debug, only verify but not submit the form
If this parameter is true, the form will not be submitted and will only be checked, which is very convenient for debugging.

$().ready(function() {
 $("#signupForm").validate({
    debug:true
  });
});

If there are multiple forms on a page and you want to set them to debug, use:

$.validator.setDefaults({
  debug: true
})

3. ignore: ignore certain elements and do not verify
ignore: ".ignore"
4. Change the position where the error message is displayed
errorPlacement: Callback
Indicates the location where the error is placed. The default is: error.appendTo(element.parent()); that is, the error message is placed after the verified element.

errorPlacement: function(error, element) { 
  error.appendTo(element.parent()); 
}

Example

<tr>
  <td class="label"><label id="lfirstname" for="firstname">First Name</label></td>
  <td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100" /></td>
  <td class="status"></td>
</tr>
<tr>
  <td style="padding-right: 5px;">
    <input id="dateformat_eu" name="dateformat" type="radio" value="0" />
    <label id="ldateformat_eu" for="dateformat_eu">14/02/07</label>
  </td>
  <td style="padding-left: 5px;">
    <input id="dateformat_am" name="dateformat" type="radio" value="1" />
    <label id="ldateformat_am" for="dateformat_am">02/14/07</label>
  </td>
  <td></td>
</tr>
<tr>
  <td class="label"> </td>
  <td class="field" colspan="2">
    <div id="termswrap">
      <input id="terms" type="checkbox" name="terms" />
      <label id="lterms" for="terms">I have read and accept the Terms of Use.</label>
    </div>
  </td>
</tr>

errorPlacement: function(error, element) {
  if ( element.is(":radio") )
    error.appendTo( element.parent().next().next() );
  else if ( element.is(":checkbox") )
    error.appendTo ( element.next() );
  else
    error.appendTo( element.parent().next() );
}

The function of the code is: generally, the error message is displayed in

, if it is radio, it is displayed In , if it is a checkbox, it is displayed behind the content.
Parameter Type Description Default Value
errorClass String specifies the css class name of the error prompt, and you can customize the style of the error prompt. "error"
errorElement String What label is used to mark errors? The default is label, which can be changed to em. "label"
errorContainer Selector displays or hides verification information. It can automatically change the container properties to display when an error message appears, and hide it when there is no error. It is of little use.
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer Selector puts error information in a container.
wrapper String What label should be used to wrap the errorELement above.
Generally, these three attributes are used at the same time to realize the function of displaying all error prompts in a container and automatically hiding it when there is no information.
errorContainer: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li"
5. Change the style of error message display
Set the style of error prompts and add icon display. A validation.css has been created in this system, which is specifically used to maintain the style of the verification file.
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;
}

6. Each field is verified through the execution function
success:String,Callback
The action after the element to be verified passes verification. If it is followed by a string, it will be treated as a css class, or it can be followed by a function.

success: function(label) {
  // set   as text for IE
  label.html(" ").addClass("checked");
  //label.addClass("valid").text("Ok!")
}

Add "valid" to the validation element with the style defined in CSS .
success: "valid"
7. Modification of verification triggering method
Although the following is of boolean type, it is recommended not to add it randomly unless you want to change it to false.
Trigger method type description default value
onsubmit Boolean Validated on submission. Set to false to use other methods to verify. true
onfocusout Boolean Validates when focus is lost (excluding checkboxes/radio buttons). true
onkeyup Boolean Validated during keyup. true
onclick Boolean Validates when checkboxes and radio buttons are clicked. true
focusInvalid Boolean After the form is submitted, the form that fails validation (the first or failed validation form that received focus before submission) will gain focus. true
focusCleanup Boolean If true then removes the error message when an element that fails validation gains focus. Avoid using it with focusInvalid. false

// 重置表单
$().ready(function() {
 var validator = $("#signupForm").validate({
    submitHandler:function(form){
      alert("submitted");  
      form.submit();
    }  
  });
  $("#reset").click(function() {
    validator.resetForm();
  });

});

8. Asynchronous verification
remote: URL
Use ajax for verification. By default, the currently verified value will be submitted to the remote address. If you need to submit other values, you can use the data option.

remote: "check-email.php"
remote: {
  url: "check-email.php",   //后台处理程序
  type: "post",        //数据发送方式
  dataType: "json",      //接受数据格式  
  data: {           //要传递的数据
    username: function() {
      return $("#username").val();
    }
  }
}

远程地址只能输出 "true" 或 "false",不能有其他输出。
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));
}, "请正确填写您的邮政编码");

注意:要在 additional-methods.js 文件中添加或者在 jquery.validate.js 文件中添加。建议一般写在 additional-methods.js 文件中。
注意:在 messages_cn.js 文件中添加:isZipCode: "只能包括中文字、英文字母、数字和下划线"。调用前要添加对 additional-methods.js 文件的引用。
10、radio 和 checkbox、select 的验证
radio 的 required 表示必须选中一个。

<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />
<input type="radio" id="gender_female" value="f" name="gender"/>
checkbox 的 required 表示必须选中。
<input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />
checkbox 的 minlength 表示必须选中的最小个数,maxlength 表示最大的选中个数,rangelength:[2,3] 表示选中个数区间。
<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />
<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />
<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />
select 的 required 表示选中的 value 不能为空。
<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">
  <option value=""></option>
  <option value="1">Buga</option>
  <option value="2">Baga</option>
  <option value="3">Oi</option>
</select>
select 的 minlength 表示选中的最小个数(可多选的 select),maxlength 表示最大的选中个数,rangelength:[2,3] 表示选中个数区间。
<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, 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>

附表:内置验证方式:

以上就是针对jQuery Validate表单验证的深入学习,希望对大家的学习有所帮助。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript在行動中:現實世界中的示例和項目JavaScript在行動中:現實世界中的示例和項目Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

了解JavaScript引擎:實施詳細信息了解JavaScript引擎:實施詳細信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python vs. JavaScript:學習曲線和易用性Python vs. JavaScript:學習曲線和易用性Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Python vs. JavaScript:社區,圖書館和資源Python vs. JavaScript:社區,圖書館和資源Apr 15, 2025 am 12:16 AM

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

從C/C到JavaScript:所有工作方式從C/C到JavaScript:所有工作方式Apr 14, 2025 am 12:05 AM

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript引擎:比較實施JavaScript引擎:比較實施Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

超越瀏覽器:現實世界中的JavaScript超越瀏覽器:現實世界中的JavaScriptApr 12, 2025 am 12:06 AM

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中