jquery Validate Form Verification plug-in _jquery

Source: Internet
Author: User
Tags extend html form

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: Binding events on the form elements that need to be validated, such as clicking, getting focus, losing focus, and setting up the corresponding execution functions for these events;
3.CSS style settings: For a form element that needs 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. Help information after the form element gets the focus (the corresponding class name "Tip" in the plug-in);

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

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.

A small example of how the jquery Validate plug-in implements form validation

Before introducing the jquery validate plug-in, you need to first introduce the file that it relies on jquery.js (jquery version 1.9 in the example); In the process of implementation, in order to better effect, I The original functionality of the jquery validate is extended in the Jquery.validate.extend.js file and the associated default options are modified; 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> 

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.

Indicate
1. The benefit of using label labels is to improve usability for mouse users. 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), success (the correct string is validated, or the execution 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>

Form validation CSS Style

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;
 }

Form Validation Effects Demo

At this point, the code for the form checksum and the application of the plug-in have all been completed.

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"
);

/******************************* 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); */< C6/>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.