Powerful jquery.validate form Verification plug-in _jquery

Source: Internet
Author: User
Tags extend html form

This example for you to share the Jquery.validate form verification of the use of methods for your reference, the specific contents are as follows

1, the preparation of form verification

Before opening the tirade, first show the results of the form validation.

1. Click on the form item to display the Help prompt

2. Start validating elements when the mouse leaves the form item

3. After the mouse left the correct, error prompts and the mouse moved in to help remind

For beginners, HTML form validation is an extremely trivial matter. To do the form validation, you need to prepare the following basic elements:

1. HTML form structure: Contains the form elements that need to be validated;

2. JS logic control: In the need to verify the form elements binding events, such as clicks, get focus, lost focus, and other events, and set up the corresponding execution functions of these events;

3. CSS style settings: For the form elements that need to be validated, the default initial style needs to be set, and the style of change after the element binding event is triggered.

Of these 3 basic elements, the creation of HTML form structure is relatively simple. The key and difficulty of form verification is how to use JS to remind users of the information about form operation timely and effectively. Here I refer to Baidu, 163 mailbox, Beijing-east and other well-known Internet enterprises registration page, summed up the form verification needs of the main information classification as follows:

1. The help information after the form element gets the focus (the corresponding class name "Tip" in the plug-in);

2. The success information of the form element validation passing (the corresponding class name "valid" in the plug-in);

3. error message for form element validation failure (corresponding class name "error" in the plug-in).

Without any plug-ins, we need to spend a lot of time writing different kinds of informational hints, thinking about switching back and forth between styles, and writing some basic validation rules. Saying: "I see farther, because I stand on the shoulders of giants." Why not just use some of the existing mature plug-ins to help us quickly write a form verification function, which can improve efficiency and allow us to devote time to our own logic.

Among the many forms validation plug-ins, the jquery validate plug-in is one of the oldest jquery Plug-ins and has been validated by different projects across the globe. It features the following:

  1. Built-in validation rules: have required, digital, email, URL and credit card number built-in validation rules;

  2. Custom validation rules: It is easy to customize the validation rules (through $.validator.addmethod (name,method,message) implementation);

  3. Simple and powerful authentication information hint: default validation information prompts, and provide custom override default information hint function (by setting the message parameters in the plug-in to achieve);

  4. Real-time validation: you can trigger validation via KeyUp or Blur events, not just when the form is submitted.

Here we select the plugin to implement a simple and beautiful example of form validation.

2 jquery Validate plug-in implementation form validation of a small example

Before introducing the jquery validate plug-in, you need to first introduce the file that it relies on jquery.js (the version of jquery in the example is 1.9); In the process of implementation, for better results, I extended the original functionality of the jquery validate in the Jquery.validate.extend.js file and modified the relevant default options; Therefore, there are three files to be introduced in the document header:

<script src= "Jquery.js" ></script>
<script src= "Lib/jquery.validate.min.js" ></script>
<script src= "Lib/jquery.validate.extend.js" ></script>


2.1 Form HTML

Form Validation 3 elements, you first need to complete the HTML form structure code to write. To make the form structure simple and clear, we wrap each element of the form in a DIV structure: using a label label to mark the name of the element, and then the form element itself.

"NOTE: 1. The advantage of using label labels is that they improve usability for the user of the mouse. When you click Text within a LABEL element, the browser automatically shifts the focus to the form control associated with the label. 2. Each form element that needs to be validated should have the ID and name attribute set to facilitate the binding of the element to the validation rule and checksum information when using the plug-in. 】

The form implementation code is as follows:

<form action= "#" method= "POST" id= "RegForm" > <fieldset> <legend>jquery-validate form checksum validation </legend&
    Gt <div class= "Item" > <label for= "username" class= "Item-label" > User name:</label> <input type= "Tex T "id=" username "name=" username "class=" Item-text "placeholder=" Set user name "autocomplete=" Off "tip=" Please enter user name "> </ div> <div class= "Item" > <label for= "password" class= "Item-label" > Password:</label> <inpu T type= "password" id= "password name=" password "class=" Item-text "placeholder=" Set password "tip=" length 6-16 characters > </d iv> <div class= "Item" > <label for= "password" class= "Item-label" > Confirm password:</label> <inp UT type= "password" name= "Repassword" class= "Item-text" placeholder= "set Confirm Password" > </div> <div class= "Item" &
      Gt <label for= "Amt" class= "Item-label" > Amount:</label> <input "text" Type= "AMT" Id= "AMT" Name= "class=" XT "PL"Aceholder= "Transaction Amount" tip= "Transaction amount must be greater than 0 and has a maximum of two decimal places" > </div> <div class= "Item" > <input type= "su
 Bmit "value=" class= "Item-submit" > </div> </fieldset> </form>

2.2 Form Validation JS logic

Then we use JS to achieve the verification of the form elements. Before checking, I extended the jquery validate plug-in to overwrite the default options. The jquery validate plugin defaults to only the correct and error-proofing prompts, and lacks our usual help tips. To solve this problem, I studied the source code of the plugin, and found that the plugin itself provided Onfocusin (called when validating elements got focus) and onfocusout (called when validating elements lost focus). By modifying these two interfaces of the default parameters, you can implement the party user to click or select elements (that is, the element gets the focus), prompt help information, and remove help information when the user mouse leaves the element (that is, the element loses focus).

In addition, the jquery validate defaults to provide real-time validation of form element input, because we require that only the user help information be turned on when input, so we need to turn off the real-time checksum of the input, so we set the onkeyup in the default parameter to NULL.

Specific extensions to improve the code I put into the new JS script jquery.validate.extend.js, the code is as follows:

/******************************* plug-in new feature-sets the default parameter of the plugin validator *****************************************/$.  Validator.setdefaults ({*/* real-time check/onkeyup:null when keyboard input is turned off,/* Add validation after successful execution function--Modify the hint content and add a new style for the correct prompt (default is valid) * * Success:
  The default correct style for function (label) {/*label is valid, which needs to be reset by Validclass, otherwise the other styles added here cannot be cleared/Label.text (""). AddClass (' valid '); },/* Rewrite the validation element after the focus of the execution function-increase [1. Help tip when the cursor moves into the element, 2. Highlight of the checksum element] Two function points/onfocusin:function (element) {this.lastactive = El
    
    ement;
    /*1. Help hint function */this.addwrapper (this.errorsfor (Element)). Hide ();
    var tip = $ (Element). attr (' tip '); if (Tip && $ (Element). Parent (). Children (". Tip"). Length = = 0) {$ (Element). Parent (). Append ("<label class=" t
    IP ' > ' + Tip + "</label>");

    /*2. Validation element highlighting/$ (element). addclass (' highlight '); Hide error label and remove error class on focus if enabled if (this.settings.focusCleanup) {if this.set Tings.unhighlight) {this.settings.unhighlight.Call (this, element, This.settings.errorClass, this.settings.validClass);
    } This.hidethese (Element) (this.errorsfor); },/* Overrides the execution function when the focus of the checksum is left-remove [1. Added help hint, 2. Validation element highlighting]*/Onfocusout:function (element) {/*1. Help message Removal * * * (elem

    ENT). Parent (). Children (". Tip"). Remove ();
    
    /*2. Verify element Highlight style remove/$ (Element). Removeclass (' highlight ');
    
    /*3. Replace the original code of the following annotation, any time the cursor leaves the element to trigger the checksum function/this.element (element); /*if (!this.checkable (Element) && (element.name in this.submitted | |!this.optional (Element)) {thi
    S.element (Element);

 }*/
  }
});

After perfecting the functionality of the plug-in, now is the play--using plug-ins to bind the validation rules and checksum information for the form elements. The jquery validate plug-in provides the Validate method to implement the element checksum of form forms, which is an object containing key-value pairs. The most commonly used keys are rules , which define the checksum rules for different elements, messages (which defines error messages for different elements), and success ( Verify the correct string or execute the function. Common validation rules are: required (required), minlength (minimum length), maxlength (maximum length), email (email format rule), URL (url format rule), date (date format rule), Rangelength (given the length range rule), Equalto (requires that the element equals another element such as Equalsto: "#password"). The following code shows how to bind a validation rule to fields such as user names, passwords, and so on in a form:

<script>
$ (document). Ready (function () {
  $ ("#regForm"). Validate ({
    rules: {
      username:{
        Required:true,
        minlength:2
      },
      password:{
        required:true,
        minlength:6,
        maxlength:16
      },
      repassword:{
        required:true,
        equalto: "#password"
      },
      amt: {
        required:true,
        amtcheck:true
      }
    },
    messages:{
      username:{
        required: "User name cannot be empty",
        minlength: " The minimum length of the username is 2 "
      },
      password:{
        required:" Password cannot be empty ",
        minlength:" Password length cannot be less than 6 characters ",
        maxlength:" Password length cannot exceed 16 characters "
      },
      repassword:{
        required:" Confirm password cannot be blank ",
        equalto:" Confirm Password and password inconsistency "
      },
      Amt: {
        Required: "The amount cannot be empty
      "
}}}); </script>

2.3 Form Validation CSS styles

Finally, add CSS styles to the page elements. There are a series of default options in the plug-in: the default error is to display a label and the error style is label.error. Above in the Jquery.validate.extend.js file, there is a success function to explain. This function is executed when the checksum is successful, and we add a checksum-correct style label.valid to the label hint tag in the function. Therefore, if you want to beautify the information in CSS, you need to design a label-related style such as error,valid style. In addition, we have added a label label with class tip in the extension functionality that is generated only when the validation element has the focus. To do this, you also need to set the tip style for the label.

The complete style file content is as follows:

body{Font-family:microsoft Yahei;
font-size:15px;  } fieldset{width:680px;  } legend{margin-left:8px;
  }. item{height:56px;
  line-height:36px;
margin:10px;
  }. Item. item-label{Float:left;
  width:80px;
Text-align:right;
  }. item-text{Float:left;
  width:244px;
  height:16px;
  padding:9px 25px 9px 5px;
  margin-left:10px;
  border:1px solid #ccc;
Overflow:hidden;
  }. item-select{Float:left;
  height:34px;
  border:1px solid #ccc;
  margin-left:10px;
  font-size:14px;
PADDING:6PX 0px;

}. item-submit{margin-left:88px;}

input.error{border:1px solid #E6594E;}

input.highlight{border:1px solid #7abd54;}
  label.error,label.tip{Float:left;
  height:32px;
  line-height:32px;
  font-size:14px;
  Text-align:left;
  margin-left:5px;
  padding-left:20px;
  color:red;
Background:url (' error.png ') no-repeat left center;
  label.tip{color: #aaa;
Background:url (' tip.png ') no-repeat left center; } label.valid{background:url (' valid.png ') no-repeat left center;
width:32px;


 }

3 Form Verification Effect Demo

At this point, the code for the form checksum and the application of the plug-in have all been completed. Run the code in the browser, showing the effect as shown below:

  

Basically meet Now most Web site form verification requirements, if you need to increase the validation rules, only in the jquery.validate.extend.js to add validation rules, examples are as follows:

/******************************* plug-in field checksum *****************************************/
$.validator.addmethod (
  "Amtcheck",
  function (value, Element) {
    /*var dotpos = Value.indexof ('. ');
    Return value > 0 && dotpos < 0 && (Dotpos > 0 && value.substring (dotpos + 1) <= 2); */< C7/>return value &&/^\d*\.? \d{0,2}$/.test (value);
  },
  "The amount must be greater than 0 and the number of decimal places does not exceed 2 digits"
);

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.