Form validation Plug-in Validation application example explain _jquery

Source: Internet
Author: User
Tags prepare

Jquery. Validation is an excellent jquery plug-in that validates client forms and provides a number of customizable properties and methods for good scalability. Now combined with the actual situation, I will often use the validation of the project to organize into an example demo, this article is to explain this example to understand the application of validation.

The validation that is involved in this example is:
User name: Length, character verification, repetitive Ajax validation (whether it already exists).
Password: Length verification, repeat input password verification.
Mail: Email address verification.
Fixed Telephone: Fixed telephone number verification in mainland China.
Mobile phone Number: China mainland mobile phone number verification.
Web address: Site URL verification.
Date: standard date format validation.
Number: integer, positive integer validation, digital range validation.
ID Card: Mainland ID card number verification.
Zip Code: Mainland ZIP code verification.
File: File type (suffix) validation, such as only allow uploading of pictures.
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> 

2. Prepare CSS Style
page style I no longer elaborate, you can write a style, you can also see the demo page source code. The key style to emphasize here is the style to display the validation 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" ce llspacing= "0" cellpadding= "0" class= "mytable" > <tr class= "table_title" > <td colspan= "2" >jquery.valida tion form validation </td> </tr> <tr> <td width= "22%" align= "right" > username:</td> <td><in Put type= "text" name= "user" id= "user" class= "input required"/> <p> username is 3-16 characters, can be numbers, letters, underscores, and Chinese </p> </td> </tr> <tr> <td align= "right" > Password:</td> <td><input type= "Password" NA Me= "Pass" id= "pass" class= "input Required"/> <p> min Length: 6 max length:16</p> </td> </tr> <t r> <td align= "right" > Confirm password:</td> <td><input type= "password" name= "repass" class= "Input Requir" Ed "/></td> </tr> </table> </form> 

It is worth mentioning that I gave the label a "required" class style, and the following will refer to its role.
4, the application of validation plug-ins
How to invoke the validation plug-in:

$ (function () {    
  var validate = $ ("#myform"). Validate ({ 
     rules:{//define validation rules 
      ... 
     }, 
     messages:{// Define hint information ... 
     }} 
); 

Rules: Defines a validation rule, in the form of Key:value, where the key is the element to be validated, and value can be a string or object. For example, verify the length of the username and not allow null:

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

In fact, we in the XHTML code can directly specify the input class attribute to required, the role is not allowed to empty, so in the JS section does not have to repeat the writing. The same authentication email, set the input class attribute directly to email.
Messages: Defines the hint information, the form key of the Key:value is the element to be validated, the value is a string or function, and the message that is prompted when the validation does not pass.

messages:{ 
 user:{ 
   required: "User name cannot be empty!" ", 
   Remote:" The username already exists, please change another username! " 
 }, 
 ...... 
} 

In this case, the validation JS is written in accordance with the rules above, validation plug-ins encapsulate a lot of basic authentication methods, as follows:
Required:true must have a value and cannot be empty
Remote:url can be used to determine whether a user name is already present, and the server-side output is true, indicating that validation passes
Minlength:6 Minimum length is 6
Maxlength:16 Maximum length is 16
Rangelength: Length Range
RANGE:[10,20] Value range is between 10-20
Email:true Authentication Message
Url:true Authentication URL URLs
Dateiso:true Validation date format ' Yyyy-mm-dd '
Digits:true can only be a number
Accept: ' gif|jpg ' only accepts pictures of GIF or JPG suffixes. Extensions that are commonly used to verify files
Equalto: ' #pass ' is equal to the value of the form field, which is often used to validate the repeated input password
In addition, I also based on the actual situation of the project to extend a few verification, validated code in Validate-ex.js, before using the need to load this JS. It can provide the following validation:
Username:true user name 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 ID Card number verification
Ip:true IP Address Verification
The verification methods provided above basically meet our requirements in most projects. If other special authentication requirements can be extended, methods such as:

JQuery.validator.addMethod ("Iszipcode", function (value, Element) {   
 var zip =/^[0-9]{6}$/;   
 return this.optional (Element) | | (Zip.test (value);   
}, "Please fill in your zip code correctly!"); 

Troubleshoot problems:
1, in the project encountered in the verification of the existence of the user name, the discovery does not support Chinese input validation. My solution is to encodeuricomponent the user name code, backstage PHP to accept the value of the UrlDecode decoding

user:{ 
  remote: { 
     URL: "chk_user.php",//server-side validator 
     type: "POST",//Submission method 
     data: {user:function () { 
       Return encodeURIComponent ($ ("#user"). Val ()); Encoded Data 
     }} 
  } 
, 

Server-Side Validator chk_user.php code:

<?php 
$request = UrlDecode (Trim ($_post[' user ')); 
Usleep (150000); 
$users = Array (' Moonlight Light ', ' jeymii ', ' Peter ', ' Helloweba '); 
$valid = ' true '; 
foreach ($users as $user) { 
  if (strtolower ($user) = = $request) 
    $valid = ' false '; 
} 
echo $valid; 
? > 

I use the server-side program is PHP, you can also use Asp,asp.net,java and so on. In addition, in order to demonstrate, the user name data is written directly on the service side, the real application is from the database out of the user name data, and to receive the client data comparison.
2. When verifying the checkbox and the radio control, the validation information does not appear behind the final control text, but directly behind the first control, which does not meet our requirements.

The workaround 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); 
} 

3, reset the form. Form form The original reset method is reset self belt

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

When you click the "Reset" button, the form elements will be reset, but after you run the validation plug-in, the validation message is not reset, and that message is not gone. Thank validation for providing a way to reset a form: Resetform ()

$ ("Input:reset"). Click (function () { 
  validate.resetform (); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.