Home > Web Front-end > JS Tutorial > Detailed explanation of using JQurey Validation form validation_jquery

Detailed explanation of using JQurey Validation form validation_jquery

WBOY
Release: 2016-05-16 16:01:28
Original
1082 people have browsed it

is an excellent plug-in that can validate client forms and provides many customizable properties and methods with good scalability. 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, repeated password verification.

Mail: Email address verification.

Landline: Mainland China landline number verification.

Mobile phone number: Mainland China mobile phone number verification.

Web address: Website URL address verification.

Date: Standard date format validation.

Number: Integer, positive integer verification, number range verification.

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.

How to use:

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>
Copy after login

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 be emphasized 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} 
Copy after login

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个字符,可以为数字、字母、下划线以及中文</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>
Copy after login

Due to space limitations, this article only intercepts a small part of the HTML code in the example. For detailed XHTML code, please refer to the page DEMO source code. It is worth mentioning that I gave the label a "required" class style, and its role will be mentioned below.

4. Apply Validation plug-in

Method to call the Validation plug-in:

$(function(){    
  var validate = $("#myform").validate({ 
     rules:{ //定义验证规则 
      ...... 
     }, 
     messages:{ //定义提示信息 
      ...... 
     } 
  }) 
}); 
Copy after login

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 
 }, 
 ...... 
} 
Copy after login

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 prompt messages, in the form of key:value, key is the element to be verified, and value is a string or function. The message is prompted when the verification fails.

messages:{ 
 user:{ 
   required:"用户名不能为空!", 
   remote:"该用户名已存在,请换个其他的用户名!" 
 }, 
 ...... 
} 
Copy after login

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 user name 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));   
}, "请正确填写您的邮政编码!"); 
Copy after login

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 in the background PHP then urldecode the accepted value

user:{ 
  remote: { 
     url: "chk_user.php", //服务端验证程序 
     type: "post", //提交方式 
     data: { user: function() { 
       return encodeURIComponent($("#user").val()); //编码数据 
     }} 
  } 
}, 
Copy after login

Code of server-side verification program chk_user.php:

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

The server program I use is PHP, you can also use ASP, ASP.NET, JAVA, etc. In addition, this example is for demonstration. The username data is written directly on the server. The real application is to take the username data from the database and compare it with the data received from the client.

2. When verifying checkbox and radio controls, the verification information will not appear after the last control text, but directly after the first control, which does not meet our requirements.

The solution is to append the following code to 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); 
} 
Copy after login

3、重置表单。Form表单原始的重置方法是reset自带

<input type="reset" value="重 置" /> 
Copy after login

点击“重置”按钮,表单元素将会重置,但是再运行Validation插件后,验证的提示信息并没重置,就是那些提示信息没有消失。感谢Validation提供了重置表单的方法:resetForm()

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

以上所述就是本文的全部内容了,希望大家能够喜欢。

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template