Jquery-validation.js is very convenient to use in front-end verification, the functions provided basically can meet most of the verification needs, such as: 1, built-in many common authentication methods, 2, can be customized error display information, 3, can be customized error display location; 4. Validation methods can be customized, 5, Ajax commit validation, etc.
But sometimes, when we do the project, we always encounter some special requirements, for example, after the validation of a single control , depending on the success of the validation, you need to call some of your own defined methods, the demand seems that the plug-in does not provide (maybe I did not find), no way, Can only look at the source (this is the benefit of open source), through the analysis of the source code, found a way to add a validation callback function to the specified control, although the need to modify a part of the source, but does not affect the use of its previous, the method can be bulk add multiple control validation callback function, add the way and add a custom rule , custom error messages, and so on, in the process of reading the source code, but also found how to control the control validation of the event trigger, and how to solve the My97datepicker date plug-in conflicts and other issues, so we suggest you look at the source code, and sometimes unexpected harvest oh.
Therefore, this article includes three aspects:
- To add a validation callback function for a control
- Control event triggering for control validation
- Resolving conflict issues with My97datepicker date plugins
Let's step through the analysis:
To add a custom callback function to the specified control
First, to add a callback function, you must find the validation method for the plug-in. In fact, in the use of the plug-in, from the intuitive operation we can find that the control validation of the trigger there are many ways, including: The loss of control focus, control content changes (in fact, KeyUp), and click the Submit button, I believe we all know that these are just appearances. After viewing the source code, can trigger the verification method has many, such as: Validate, form, checkform and element, but this is still the appearance, with our programmer's sense of smell, the real verification function is definitely only one, after in-depth investigation, before each method has called the check method, A sentence was found 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 where the validation logic is actually called, so we need to place the custom validation callback function in the check method, with the modified code as follows (the yellow part is the added code):
Checkfunction(Element) {element= This. Validationtargetfor ( This. Clean (element)); varRules =$ (Element). Rules (); varDependencymismatch =false; for(varMethodinchrules) { varRule ={method:method, Parameters:rules[method]}; Try { varresult = $.validator.methods[method].call ( This, Element.value.replace (/\r/g, ""), element, rule.parameters); //If a method indicates the field is optional and therefore valid, //don ' t mark it as valid when there is 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);
//Validation Failure callback function if (element.id . 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); Throwe; } } if(Dependencymismatch)return; if( This. Objectlength (rules)) This. Successlist.push (Element);
//Verify success callback function if (element.id in this. settings.validcallbackforelement) { this. settings.validcallbackforelement[element.id].success (); }
return true; },
Here, in order to be consistent with other custom properties of the plugin, we define an object with the following structure:
validcallbackforelement:{yourcontrolid1:{Success:function(){ //Verify Successful callback}, fail:function(){ //Validation Failure Callback}}, yourcontrolid2:{success:function(){ //Verify Successful callback}, fail:function(){ //Validation Failure Callback } },}
It is then placed into the parameters of the Validate method, as shown in the following example (changing "yourControlId1" and "yourControlId2" to your own control ID):
$ ("#form1"). Validate ({rules: {yourControlId1 : {required:true}, YourControlId2: {required:true, MaxLength:500 } }, //End Rulemessages: {yourControlId1: {required:"Cannot be empty"}, YourControlId2: {required:"Cannot be empty", MaxLength:"The content is too long"}}, Errorplacement:function(Error, Element) {if(Element.context.name = = "YourControlId1") {error.appendto (document.getElementById ("Yourcontrolid1_error")); } Else if(Element.context.name = = "YourControlId2") Error.appendto (document.getElementById ("Yourcontrolid2_error")); }, Submithandler:function(form) {ajaxsubmit (); }, Validcallbackforelement: {yourControlId1: {success:function() { //validation successful callback for control YOURCONTROLID1}, fail:function() { //validation failure callback for control YOURCONTROLID1}}, YourControlId2: {success: /c0>function() { //validation successful callback for control YOURCONTROLID2}, fail:function() { //validation failure callback for control YOURCONTROLID2 } } } }); //End Validate Function
In the constructor, the Validcallbackforelement object is merged into multiple This.settings objects, so it needs to be written when called: this.settings.validcallbackforelement[ Element.id].success ();
Because we don't necessarily add a callback function to all the validation controls, we need to first determine if the control has a corresponding destroy function at the time of the call, so the calling code is changed to:
if (element.id. settings.validcallbackforelement) {This . settings.validcallbackforelement[ Element.id].fail ();}
Here, the question of how to add a custom validation callback function to the specified control has been resolved.
Validation Trigger issue:
When using jquery-validation, it is found that the KeyUp and Focusout events of the control cannot trigger validation until the validation method is invoked, such as when we open a page without clicking the Submit button, so that the form is not validated. At this point we put the cursor on the input control, and then nothing to write, when we let the input lose focus, we will find, and there is no prompt that input is a required error message, because The Jquery-validation plug-in validates the form by storing the error information in the ERRORMAP variable, with the ERRORMAP structure as follows:
errormap{ yourControlId1:"Required", yourControlId2:"content too Long", ...}
The Errormap is then merged into the This.submited object, and in the Focusout and KeyUp events, the ID of the control is determined in this.submited, and if it does, the code is as follows:
function (element, event) {
if (!that.checkable (Element) && (element.name in that.submitted | |!that.optional (Element))) {
That.element (Element);
}
function
if (element.name in this.submitted This
This
}
},
Therefore, the control's focusout and KeyUp validation will not be activated until the form is validated, and if you want to enable Focusout and KeyUp to trigger validation at the outset, you can remove the red part of the code here.
Conflict issues with My97datepicker date control:
Believe that My97datepicker is a date control that many people have used, the control conflicts with the Jquery-validation plug-in, causing the Focusout event of the Jquery-validation plugin to fail to trigger validation. May be because these two things are registered Focusout event, so caused the conflict, originally wanted to see the source of My97datepicker, opened after found to be compressed version, it seems to be confused, so if the page in the same time using these two things, Can only modify the jquery-validation, the following modifications may be made:
onfocusout: function // Modify the code here, otherwise it will conflict with My97datepicker. The var that = this SetTimeout ( function () { if (!that.checkable (Element) && (element.name in that.submitted | | ! that.optional (Element))) {that.element (element); ", 100); },
Validation callback method for adding controls to the Jquery-validation plug-in