国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial Example explanation of form validation plug-in Validation application_jquery

Example explanation of form validation plug-in Validation application_jquery

May 16, 2016 pm 03:37 PM

jquery.Validation is an excellent jquery plug-in that can validate client forms and provides many customizable properties and methods with good scalability. Now combined with the actual situation, I have organized the verifications that are often used in the project into an example DEMO. This article is to understand the application of Validation by explaining this example.

The verifications involved in this example are:
Username: length, character verification, repeatability ajax verification (whether it already exists).
Password: Length verification, repeat password verification.
Email: Email address verification.
Landline: Mainland China landline number verification.
Mobile phone number: Mainland China mobile phone number verification.
URL: Website URL address verification.
Date: Standard date format validation.
Number: Integer, positive integer validation, numeric range validation.
ID card: Mainland China ID number verification.
Postal code: Mainland postal code verification.
File: File type (suffix) verification, for example, only images are allowed to be uploaded.
IP: IP address verification.
Verification code: verification code ajax verification.
Usage:
1. Prepare jquery and jquery.validate plug-ins

<script type="text/javascript" src="js/jquery.js"></script> 
<script type="text/javascript" src="js/jquery.validate.js"></script> 

2. Prepare CSS styles
I won’t go into details about the page style. You can write your own style, or you can refer to the DEMO page source code. The key style to emphasize here is the style to display verification information:

label.error{color:#ea5200; margin-left:4px; padding:0px 20px; 
background:url(images/unchecked.gif) no-repeat 2px 0 } 
label.right{margin-left:4px; padding-left:20px; background: 
url(images/checked.gif) no-repeat 2px 0} 

3. XHTML

<form id="myform" action="#" method="post"> 
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="mytable"> 
 <tr class="table_title"> 
  <td colspan="2">jquery.validation 表單驗證</td> 
 </tr> 
 <tr> 
  <td width="22%" align="right">用戶名:</td> 
  <td><input type="text" name="user" id="user" class="input required" /> 
  <p>用戶名為3-16個字符,可以為數(shù)字、字母、下劃線以及中文</p></td> 
 </tr> 
 <tr> 
  <td align="right">密碼:</td> 
  <td><input type="password" name="pass" id="pass" class="input required" /> 
  <p>最小長度:6 最大長度:16</p> 
  </td> 
 </tr> 
 <tr> 
  <td align="right">確認密碼:</td> 
  <td><input type="password" name="repass" class="input required" /></td> 
 </tr> 
</table> 
</form> 

It is worth mentioning that I gave the label a "required" class style, and its function will be mentioned below.
4. Apply Validation plug-in
Method to call the Validation plug-in:

$(function(){    
  var validate = $("#myform").validate({ 
     rules:{ //定義驗證規(guī)則 
      ...... 
     }, 
     messages:{ //定義提示信息 
      ...... 
     } 
  }) 
}); 

rules: Define verification rules, in the form of key:value, key is the element to be verified, and value can be a string or object. For example, verify the length of the username and not allow it to be empty:

rules:{ 
 user:{ 
   required:true, 
   maxlength:16, 
   minlength:3 
 }, 
 ...... 
} 

In fact, we can directly specify the class attribute of input as required in the XHTML code. The function is not to allow it to be empty, so that there is no need to write it repeatedly in the JS part. In the same way to verify email, etc., directly set the class attribute of input to email.
messages: Define the prompt message. In the form of key:value, key is the element to be verified, and the value is a string or function. The message is prompted when the verification fails.

messages:{ 
 user:{ 
   required:"用戶名不能為空!", 
   remote:"該用戶名已存在,請換個其他的用戶名!" 
 }, 
 ...... 
} 

The verification JS involved in this example is written according to the above rules. The Validation plug-in encapsulates many basic verification methods, as follows:
required:true must have a value and cannot be empty
remote:url can be used to determine whether the username already exists. The server outputs true, indicating that the verification is passed
minlength:6 The minimum length is 6
maxlength:16 The maximum length is 16
rangelength: length range
range:[10,20] The value range is between 10-20
email:true verification email
url:true Verification URL
dateISO:true Verify date format 'yyyy-mm-dd'
digits:true can only be numbers
accept:'gif|jpg' only accepts pictures with gif or jpg suffix. Extensions commonly used to verify files
equalTo:'#pass' is equal to which form field value, often used to verify repeated password entry
In addition, I also expanded several verifications based on the actual situation of the project. The verification code is in validate-ex.js. This JS needs to be loaded before use. It provides the following verification:
userName:true Username can only include Chinese characters, English letters, numbers and underscores
isMobile:true mobile phone number verification
isPhone:true Mainland mobile phone number verification
isZipCode:true zip code verification
isIdCardNo:true Mainland China ID number verification
ip:true IP address verification
The verification methods provided above basically meet our needs in most projects. If there are other special verification requirements, it can be expanded, as follows:

jQuery.validator.addMethod("isZipCode", function(value, element) {   
 var zip = /^[0-9]{6}$/;   
 return this.optional(element) || (zip.test(value));   
}, "請正確填寫您的郵政編碼!"); 

Troubleshooting:
1. When verifying whether the user name exists in the project, it was found that Chinese input verification is not supported. My solution is to encode the user name with encodeURIComponent, and then use the background PHP to urldecode the accepted value

user:{ 
  remote: { 
     url: "chk_user.php", //服務(wù)端驗證程序 
     type: "post", //提交方式 
     data: { user: function() { 
       return encodeURIComponent($("#user").val()); //編碼數(shù)據(jù) 
     }} 
  } 
}, 

Code of server-side verification program chk_user.php:

<&#63;php 
$request = urldecode(trim($_POST['user'])); 
usleep(150000); 
$users = array('月光光', 'jeymii', 'Peter', 'helloweba'); 
$valid = 'true'; 
foreach($users as $user) { 
  if( strtolower($user) == $request ) 
    $valid = 'false'; 
} 
echo $valid; 
&#63;> 

我使用的服務(wù)端程序是PHP,您也可以使用ASP,ASP.NET,JAVA等。此外本例為了演示,用戶名數(shù)據(jù)是直接寫在服務(wù)端的,真正的應(yīng)用是從數(shù)據(jù)庫里取出的用戶名數(shù)據(jù),來和接收客戶端的數(shù)據(jù)進行對比。
2、在驗證checkbox和radio控件時,驗證信息不會出現(xiàn)在最后的控件文本后面,而是直接跟在第一個控件的后面,不符合我們的要求。

解決辦法是在validate({})追加以下代碼:

errorPlacement: function(error, element) { 
  if ( element.is(":radio") ) 
    error.appendTo ( element.parent() ); 
  else if ( element.is(":checkbox") ) 
    error.appendTo ( element.parent() ); 
  else if ( element.is("input[name=captcha]") ) 
    error.appendTo ( element.parent() ); 
  else 
    error.insertAfter(element); 
} 

3、重置表單。Form表單原始的重置方法是reset自帶

<input type="reset" value="重 置" /> 

點擊“重置”按鈕,表單元素將會重置,但是再運行Validation插件后,驗證的提示信息并沒重置,就是那些提示信息沒有消失。感謝Validation提供了重置表單的方法:resetForm()

$("input:reset").click(function(){ 
  validate.resetForm(); 
}); 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

What's the Difference Between Java and JavaScript? What's the Difference Between Java and JavaScript? Jun 17, 2025 am 09:17 AM

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.

See all articles