Home >Web Front-end >JS Tutorial >Example explanation of form validation plug-in Validation application_jquery
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个字符,可以为数字、字母、下划线以及中文</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:{ //定义验证规则 ...... }, 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", //服务端验证程序 type: "post", //提交方式 data: { user: function() { return encodeURIComponent($("#user").val()); //编码数据 }} } },
Code of server-side verification program chk_user.php:
<?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; ?>
我使用的服务端程序是PHP,您也可以使用ASP,ASP.NET,JAVA等。此外本例为了演示,用户名数据是直接写在服务端的,真正的应用是从数据库里取出的用户名数据,来和接收客户端的数据进行对比。
2、在验证checkbox和radio控件时,验证信息不会出现在最后的控件文本后面,而是直接跟在第一个控件的后面,不符合我们的要求。
解决办法是在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(); });