Verification callback Method for adding controls to the jquery-validation plug-in

Source: Internet
Author: User

Verification callback Method for adding controls to the jquery-validation plug-in
Jquery-validation.js is very convenient to use in front-end verification, provides the function can basically meet most of the verification requirements, such as: 1, built into a lot of common verification methods; 2. You can customize the error display information. 3. You can customize the error display location. 4. You can customize the verification method. 5. Submit the ajax verification, we always encounter some special requirements when doing a project. For example, after a single control verification is completed, we need to call some methods defined by ourselves based on whether the verification is successful or not, this requirement seems to have not been provided by the plug-in (maybe I did not find it). No way, I can only look at the source code (this is the benefit of Open Source). Through the analysis of the source code, A method was found to add a verification callback function to the specified control. Although some source code needs to be modified, it does not affect its previous use, this method allows you to add verification callback functions for multiple controls in batches. The addition method is similar to adding custom rules and custom error messages. When you read the source code, we also discovered how to control the event triggering of control verification, and how to resolve conflicts with the My97DatePicker date plug-in. So it is recommended that you read the source code, sometimes unexpected gains. Therefore, this article includes three aspects: add the verification callback function of the control to control the event triggering of the control verification to solve the conflict with the My97DatePicker date plug-in. Next we will analyze it step by step: to add a custom callback function to a specified control, you must find the authentication method of the plug-in before adding the callback function. In fact, when using this plug-in, we can find that there are multiple ways to trigger control verification, including the loss of control focus, changes in the control content (in fact, keyup), and click the submit button. I believe everyone knows that these are just representations. After checking the source code, there are many methods that can trigger verification, such as validate, form, checkForm, and element. However, this is still the representation of our programmers, there must be only one real verification function. After in-depth investigation, each of the preceding Methods calls the check method and finds a sentence in the check method: var result = $. validator. methods [method]. call (this, element. value. replace (/\ r/g, ""), element, rule. parameters). As you can see, this code is the place where the verification logic is actually called. Therefore, we need to place the custom verification callback function in the check method, the modified code is as follows (the yellow part is the added code): copy the code check: function (element) {element = this. validationTargetFor (this. clean (element); v Ar rules = $ (element ). rules (); var dependencyMismatch = false; for (var method in rules) {var rule = {method: method, parameters: rules [method]}; try {var result = $. validator. methods [method]. call (this, element. value. replace (/\ r/g, ""), element, rule. parameters); // if a method indicates that the field is optional and therefore valid, // don't mark it as valid when there are no other rules if (Result = "dependency-mismatch") {dependencyMismatch = true; continue;} dependencyMismatch = false; if (result = "pending") {this. toHide = this. toHide. not (this. errorsFor (element); return;} if (! Result) {this. formatAndAdd (element, rule); // if (element. id in this. settings. validCallbackForElement) {this. settings. validCallbackForElement [element. id]. fail () ;}return false ;}} catch (e) {this. settings. debug & window. console & console. log ("exception occured when checking element" + element. id + ", check the '" + rule. method + "'method", e); throw e ;}} if (dependencyMismatch) r Eturn; if (this. objectLength (rules) this. successList. push (element); // callback function if (element. id in this. settings. validCallbackForElement) {this. settings. validCallbackForElement [element. id]. success () ;}return true ;}, copy the code here. To be consistent with other custom attributes of the plug-in, we define an object with the following structure: copy the code validCallbackForElement: {yourControlId1: {success: function () {// callback for successful verification}, fail: function () {// callback for failed verification}, yourControlId2: {success: funct Ion () {// callback for successful verification}, fail: function () {// callback for failed verification},} copy the code and put it into the parameters of the validate method, for example, replace "yourControlId1" and "yourControlId2" with your own control id when modifying: copy the code $ ("# form1 "). validate ({rules: {yourControlId1: {required: true}, yourControlId2: {required: true, maxlength: 500 }}, // end rule messages: {yourControlId1: {required: "cannot be blank"}, yourControlId2: {required: "cannot be blank", maxlength: "The content is too long" }}, errorPlacement: func Tion (error, element) {if (element. context. name = "yourControlId1") {error. appendTo (document. getElementById ("yourcontro1_1_error");} else if (element. context. name = "yourControlId2") error. appendTo (document. getElementById ("yourcontro4102_error") ;}, submitHandler: function (form) {ajaxSubmit () ;}, validCallbackForElement: {yourControlId1: {success: function () {// callback for successful verification of the control yourControlId1}, Fail: function () {// control yourControlId1 verification failure callback}, yourControlId2: {success: function () {// control yourControlId2 verification success callback}, fail: function () {// control yourControlId2 verification failure callback }}}); // end validate function copy code in the constructor, The validCallbackForElement object will be merged more than this. settings object. Therefore, it must be written as: this. settings. validCallbackForElement [element. id]. success (); because we do not necessarily add a callback function to all verification controls, we need to first determine whether the control has a corresponding destroy function during the call. In this way, the call code is changed to: if (Element. id in this. settings. validCallbackForElement) {this. settings. validCallbackForElement [element. id]. fail ();} Here, the problem of how to add a custom verification callback function to the specified control has been solved. The following provides a simple example: the example program that adds the control Verification callback method verification trigger problem is found when jquery-validation is used, before the verification method is called, the keyup and focusout events of the control cannot trigger verification. For example, if we open a page and do not click the submit button, the form will not be verified. At this time, we place the cursor on the input control, then, nothing is written, and the focus of the input is lost. At this time, we will find that the input is not prompted to be a required error message because, the jquery-validation plug-in saves the error information in the errorMap variable when verifying the form. The structure of errorMap is as follows: errorMap {yourControlId1: "required", yourControlId2: "The content is too long ",......} then combine errorMap to this. in the submited object, this is determined in the focusout and keyup events. in submited Whether the id of the control exists. if yes, verification is performed. The Code is as follows: copy the code onfocusout: function (element, event) {if (! That. checkable (element) & (element. name in that. submitted |! That. optional (element) {that. element (element) ;}, onkeyup: function (element, event) {if (element. name in this. submitted | element = this. lastElement) {this. element (element) ;}}, copy the code. Therefore, the focusout and keyup verification of the control will be activated only after Form Verification is executed. If you want to trigger verification for focusout and keyup at the beginning, you can remove the red code here. There was a problem with the description of this part. The purpose of verification cannot be achieved only by removing the red part of the code. We can see from the source code that, the author of the jquery-validation plug-in has strict control over this field. It depends not only on the submitted attribute, but also on the control value, the intention of this plug-in is to ensure that the control does not call the verification method of the control before it has no value and no form verification. This can be seen through the logic in the onfocusout and onkeyup events, the logic of the two parts is not the same. Therefore, if you want to trigger the verification method for controls with null values through focusout and keyup before form verification, You need to modify many places, which obviously does not conform to the idea of writing the plug-in. Conflict with the My97DatePicker date control I believe that My97DatePicker is a date control that many people have used. This control will conflict with the jquery-validation plug-in, as a result, the focusout event of the jquery-validation plug-in cannot trigger verification. It may be because both of these two items have registered the focusout event, which leads to a conflict. I would like to see the source code of My97DatePicker, after opening the file, we found that it was a compressed version, which seemed to be confused. Therefore, if you use both of these two items on the page, you can only modify jquery-validation. You can make the following modifications: copy the code onfocusout: function (element, event) {// modify the code here. Otherwise, it will conflict with My97DatePicker, and will not verify var that = this when the focus is lost; setTimeout (function () {if (! That. checkable (element) & (element. name in that. submitted |! That. optional (element) {that. element (element) ;}, 100 );},

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.