JQuery.Validate.js verifies slow processing when the form tag is many.

Source: Internet
Author: User

Recently, there are more than 200 labels in a form form that have encountered in the project. When you submit a form, the page waits a long time, and even the page crashes.

The main reason is that it costs a lot of time to use JQuery.Validate.js for form validation. These times are mainly used in two places:

1. The label check in the form corresponds to the Checkform () method in JQuery.Validate.js.

2. After checking the label you need to display error or success information corresponding to the ShowErrors () method in JQuery.Validate.js.

Previously we were using the jquery.validate.js-1.8.0 version, I updated to the latest jquery.validate.js-1.15.1 version and found that the verification time was not significantly optimized.

Instead, there will be conflicts with the previous version, where there is no way to validate hidden controls, such as a third-party HTML edit box plug-in, which hides a textarea control later, but the newer version is ignored. The problem is that the new version of JS defaults to skipping elements that are not visible on the page.

The 1.8.0 version of ignore:[] will be changed to ". Hidden" in Checkform () to filter out all the invisible elements in the page by default.

This is 1.15.1 Ways to Checkform:

function () {            this. PrepareForm ();              for var  This this. elements ()); elements[i]; i++ ) {                this. Check (elements[i]);            }             return  This . valid ();        },
Elementsfunction() {            varValidator = This, Rulescache= {}; //Select all valid inputs inside the form (no submit or reset buttons)            return$( This. Currentform). Find ("Input, select, textarea, [contenteditable]"). Not (": Submit,: RESET,: Image,:d isabled"). Not ( This. Settings.ignore)//In this place will filter the hidden elements, the returned elements will be a lot less hidden elements: filter (function() {                varName = This. name | | $( This). attr ("name");//For contenteditable                if(!name && Validator.settings.debug &&window.console) {console.error ("%o has no name assigned", This ); }                //Set form expando on contenteditable                if( This. Hasattribute ("contenteditable" ) ) {                     This. Form = $ ( This). Closest ("form") [0 ]; }                //Select only the first element for each name, and only those with rules specified                if(NameinchRulescache | | !validator.objectlength ($ ( This). Rules ())) {return false; } rulescache[Name]=true; return true;        } ); },

This kind of processing can really reduce the check of many unnecessary elements. But it's not obvious how much time is being tested here.

This, however, causes the project to become incompatible because hidden elements such as HTML edit boxes and other artifacts that need to be validated are also hidden.

For the purpose of the project, I have changed the Ignore parameter in this parameter defaults to input[type= "hidden", which solves the problem of compatibility. Because this only ignores the "Type=hidden" element set in the <input> tag, the check is ignored.

Saying so much does not mention the aspect of how to improve the performance of validation. The following discussion, because I am also a side dish, I hope the great God do not spray.

As mentioned above, the time spent on verification is mainly two functions, so let's start with these two functions:

1.checkForm ().

From the above we have already seen, set the value of ignore to filter out some of the hidden elements itself is a checkform () function to perform the optimization. But here does not play a substantial role, because often the hidden elements of the form is not a lot, want to get a bigger ascension should be shown in the page but do not need to verify the label to filter, really do only check the label element to be checked. One way to do this online is to add a class like "class= ' Validate-ignore" to each element tag that does not need a check, and then filter out such elements that do not need to be validated in the elements () method. This practice I did not go to practice, because there are too many forms in the project, so it is a little unrealistic to add a new class to each one. Interested friends can go and study.

2.showErrors ().

This approach costs a lot of time. Because this method causes the HTML DOM tree to change, to display and modify the error or correct prompt information.

The native ShowErrors method is as follows

Each elment in the default page that needs to be validated goes through the Else branch to execute the defaultshowerrors () function, which is the entry that alters the structure of the DOM tree. So the logic of adding a judgment here is going to be a lot more time-boosting. The new judgments are as follows:

ShowErrors:function(Errors) {if(Errors) {varValidator = This; //ADD items to Error list and map$.extend ( This. Errormap, errors);  This. errorlist = $.map ( This. Errormap,function(message, name) {return{message:message, element:validator.findByName (name) [0 ]                    };                } ); //Remove items from success list                 This. successlist = $.grep ( This. Successlist,function(Element) {return! (Element.nameincherrors);            } ); }            if( This. Settings.showerrors) {                 This. Settings.showErrors.call ( This, This. Errormap, This. errorlist); } Else {                    varAnyelementsneedupdate =false;//parameter indicates whether the element in the DOM tree needs to be updated                     for(vari = 0; I < This. errorlist.length; i++) {                        if(!$( This. errorlist[i].element). Hasclass ( This. Settings.errorclass)) {Anyelementsneedupdate=true;//1. If the element that was previously verified to have the error has been modified correctly, without this errorclass, you need to update element                             Break; }                    }                    if(!anyelementsneedupdate) {                         for(vari = 0; I < This. successlist.length; i++) {                            if($( This. Successlist[i]). Hasclass ( This. Settings.errorclass)) {Anyelementsneedupdate=true;//2. When the previously validated element now contains this errorclass, it needs to be updated                                 Break; }                        }                    }                    if(anyelementsneedupdate) {//if one of the above two situations needs to be updated DOM element, otherwise should not go to call defaultshowerrors ();                         This. Defaultshowerrors (); }            }        },

From this it can be seen clearly that the checkform () function time has not changed much. But the showerrors () time becomes the previous one-tenth.

After testing this modification has no effect on the verification function, and the performance has improved a lot.

Reference: Http://stackoverflow.com/questions/5542014/jquery-validate-large-forms-script-running-slowly.

JQuery.Validate.js verifies slow processing when the form tag is many.

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.