jQuery.validationEngine.js学习
项目中使用到了这个插件,抽了个空,看了一下。
(function($){ var method ={} $.fn.validationEngine = function(){} $.validationEngine = {} $(function(){$.validationEngine.defaults.promptPosition = methods.isRTL()?'topLeft':"topRight"}); })(jQuery)
看一下结构,还是比较清晰的。jQuery的dom对象直接调用就行了,下面我拿jQuery官方上的一个例子来说明
看一下例子:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>JQuery Validation Engine</title> <link rel="stylesheet" href="../css/validationEngine.jquery.css" type="text/css"/> <link rel="stylesheet" href="../css/template.css" type="text/css"/> <script src="../js/jquery-1.8.2.min.js" type="text/javascript"> </script> <script src="../js/languages/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"> </script> <script src="../js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"> </script> <script> jQuery(document).ready(function(){ // binds form submission and fields to the validation engine jQuery("#formID").validationEngine();//初始化 }); </script> </head> <body> <p> This demonstration shows the prompt position adjustments <br/> </p> <div id="test" class="test" style="150px;">This is a div element</div> <form id="formID" class="formular" method="post" action=""> <fieldset> <label> <span>Fields are required : </span> <input value="" class="validate[required] text-input" type="text" name="req" id="req" data-prompt-position="topRight:-70" /> </label> <label> <input value="" class="validate[required] text-input" type="text" name="req2" id="req2" data-prompt-position="topRight:-30" /> </label> <label> <span>Additional info:</span> <textarea class="validate[required]" id="add" style="250px;height:50px;" data-prompt-position="bottomRight:-70,3"></textarea> </label> <br/> <br/> </fieldset> <input class="submit" type="submit" value="Validate & Send the form!"/><hr/> </form> </body> </html>
可以看到页面直接调用了validationEngine方法。
$.fn.validationEngine = function(method) { var form = $(this);//获取form对象 if(!form[0]) return form; // stop here if the form does not exist 如果不是jQuery的dom对象则返回 if (typeof(method) == 'string' && method.charAt(0) != '_' && methods[method]) { // make sure init is called once if(method != "showPrompt" && method != "hide" && method != "hideAll") methods.init.apply(form);
return methods[method].apply(form, Array.prototype.slice.call(arguments, 1));//支持传入原型上的方法执行该方法 } else if (typeof method == 'object' || !method) { //该例子中method为undefined // default constructor with or without arguments methods.init.apply(form, arguments);//调用方法对象中的init方法 return methods.attach.apply(form);//调用方法对象中的attach方法 } else { $.error('Method ' + method + ' does not exist in jQuery.validationEngine'); } }
这里,可以看到如果想让验证控件不能工作,在validationEngine方法中传入三种参数,showPrompt,hide,hideAll。等会后面分析,会看到,只要代码处调用传入这个三个参数,插件都将不会工作,因为其中的methods.init,attach方法没有被执行,初始化所导致的结果。其实,如果你传入像'1'这样的参数,插件一样不会工作,不过它会报错,走入最后一个判断,调用$.error抛出异常。
以下是引擎的工作流程
在使用jquery.validationEngine.js时还需要一个js文件:包括许多语言包,这里我们就用en包做个示范,引入jQuery.validationEngine-en.js
(function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules ={} } }; $.validationEngineLanguage.newLang(); })(jQuery);
validationEngineLanguage方法直接添加到jquery原型上,这里默认没有初始化任何东西,实际开发中,根据需求做适当修改,代码中默认执行一遍$.validationEngineLanguage.newLang(),让$.validationEngineLanguage拥有allRules属性,留心看一下这个allRules的内容
"required": { // Add your regex rules here, you can take telephone as an example "regex": "none", "alertText": "* This field is required", "alertTextCheckboxMultiple": "* Please select an option", "alertTextCheckboxe": "* This checkbox is required", "alertTextDateRange": "* Both date range fields are required" } "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([+][0-9]{1,3}[ .-])?([(]{1}[0-9]{2,6}[)])?([0-9 .-/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/, "alertText": "* Invalid phone number" } ....
类似页面写入一个required,这个字符串会关联许多信息,包括为空的弹出信息,phone这个字符串则关联了匹配的正则和弹出的错误信息。如果需要添加新的匹配功能,这里是可以添加的。
Method.init
init: function(options) { var form = this; if (!form.data('jqv') || form.data('jqv') == null ) { options = methods._saveOptions(form, options); // bind all formError elements to close on click $(document).on("click", ".formError", function() {//让html标签去监听拥有formError类的元素绑定click事件 $(this).fadeOut(150, function() {//实现淡出效果 // remove prompt once invisible $(this).parent('.formErrorOuter').remove();//删除其父节点 $(this).remove();//删除本身节点 }); }); } return this; }
这里.formError是弹出的错误信息的类,这里在init方法中给这些弹出信息添加了click事件,用于关闭它们。
Method._saveOptions
_saveOptions: function(form, options) { // is there a language localisation ? if ($.validationEngineLanguage) var allRules = $.validationEngineLanguage.allRules; else //这里的else语句就是else下面的紧跟它的第一句代码,不推荐这样写。 $.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page"); // --- Internals DO NOT TOUCH or OVERLOAD --- // validation rules and i18 $.validationEngine.defaults.allrules = allRules; var userOptions = $.extend(true,{},$.validationEngine.defaults,options);//保存错误规则 form.data('jqv', userOptions);//将userOptions信息保存在jqv属性中 return userOptions; }
主要是导入jQuery.validationEngine-en.js的内容,将信息保存到jqv属性中,最后返回该信息。
Method.attach
attach: function(userOptions) {//调用者是被验证的form var form = this; var options; if(userOptions) options = methods._saveOptions(form, userOptions); else options = form.data('jqv');//读取form的jqv信息 //寻找data-validation-engine属性中拥有validate的标签 options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class"; if (options.binded) { //绑定blur事件,如果没有data-validation-engine属性的,那必须拥有包含validate字符串的类,且不是checkbox,radio或者是类datepicker(时间控件)的元素将拥有blur事件 //为checkbox,radio必须要有validate的控件绑定click事件 //单独为时间控件绑定blur时间,传入{'delay':300} // delegate fields form.on(options.validationEventTrigger, "["+options.validateAttribute+"*=validate]:not([type=checkbox]):not([type=radio]):not(.datepicker)", methods._onFieldEvent); form.on("click", "["+options.validateAttribute+"*=validate][type=checkbox],["+options.validateAttribute+"*=validate][type=radio]", methods._onFieldEvent); form.on(options.validationEventTrigger,"["+options.validateAttribute+"*=validate][class*=datepicker]", {"delay": 300}, methods._onFieldEvent); } if (options.autoPositionUpdate) { $(window).bind("resize", { "noAnimation": true, "formElem": form }, methods.updatePromptsPosition); } //为拥有data-validation-engine-skip属性的a标签和button,input标签,类拥有validate-skip字段的a标签和button,input标签绑定click事件。 form.on("click","a[data-validation-engine-skip], a[class*='validate-skip'], button[data-validation-engine-skip], button[class*='validate-skip'], input[data-validation-engine-skip], input[class*='validate-skip']", methods._submitButtonClick); form.removeData('jqv_submitButton');//删除jqv_submitButton信息 // bind form.submit form.on("submit", methods._onSubmitEvent);//绑定submit return this; }
绑定了基本上控件的触发事件,这里还要提到的是在我们提交form的时候,会触发插件内容的submit的监听事件,实际上插件会在你提交之前再去帮你检查一遍控件。如果全满足条件了,则将会提交。可以看到很多的控件基本上绑定触发的事件都是method._onFieldEvent方法
这里我们拿_onFieldEvent来看一下。
_onFieldEvent: function(event) { var field = $(this); var form = field.closest('form, .validationEngineContainer');//找到form对象 var options = form.data('jqv');//读取jqv属性信息 options.eventTrigger = "field"; // validate the current field window.setTimeout(function() { methods._validateField(field, options); if (options.InvalidFields.length == 0 && options.onFieldSuccess) { options.onFieldSuccess(); } else if (options.InvalidFields.length > 0 && options.onFieldFailure) { options.onFieldFailure(); } }, (event.data) ? event.data.delay : 0); }
将执行函数放入setTimeout中,这里考虑到一个datepicker插件的问题。
这里_validateField的全部代码就不贴了,分析一下里面几块重要的部分
var rulesParsing = field.attr(options.validateAttribute);//获取控件的类或者data-validation-engine属性 var getRules = /validate[(.*)]/.exec(rulesParsing);//var getRules = rulesParsing.match(/validate[(.*)]/);数组中第一个是匹配整条正则,第二个成员是匹配子表达式 if (!getRules) return false;//如果数组为空,表示不匹配,则返回 var str = getRules[1];//获取子表达式匹配的内容 var rules = str.split(/[|,|]/);//将以类似[,],','分开字符串,考虑validate[]中嵌套多个内容 for (var i = 0; i < rules.length; i++) { rules[i] = rules[i].replace(" ", "");//去掉空白 // Remove any parsing errors if (rules[i] === '') { delete rules[i];//删除空的规则 } }
这里是对rules的解析,将原来的例子修改一下
<input value="" class="validate[required,custom[email]] text-input" type="text" name="req" id="req" data-prompt-position="topRight:-70" />
这里为什么不直接写validate[required,email],或者是validate[required,xx[email]](xx不是custom)了?带着这些疑问,我们来看一下源码。
源码中getRules使用的是exec来获取匹配的结果文本,这里的匹配结果是[validate[reuqired,custom[email]] text-input,required,custom[email]]。再看str,它的值为required,custom[email],再经过split分隔,rule将变为[required,custom,email,''],最后经过for循环遍历将将空字符串的成员delete掉,最后结果是[required,custom,email,undefined]。至于为什么要加这个custom,不急,我们慢慢看。
其实这个插件将控件需要执行的验证规则都写在了class类中,也就是说我们在validate[]中写了一些规则,那么控件将会执行这些规则,其实required则表示为必填,email则表示为输入email格式。两者必须同时满足。
源码下面会再经历一次for循环,但是注意,这里多了一个switch判断,将rules中有的规则一一过滤出来,执行相应的方法。如果你留心看一下这个switch,你就会发现,这里面根本没有email的选择类型,所以说你直接在页面上写成validate[required,email]是不会有效果的。我们可以看到有custom的判断。进入看一下这个custom,到底是什么
case "custom": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom); break;
_getErrorMessage这个方法说白了,就是获取错误信息,执行传入的回相对应的调函数
_getErrorMessage:function (form, field, rule, rules, i, options, originalValidationMethod) { // If we are using the custon validation type, build the index for the rule. // Otherwise if we are doing a function call, make the call and return the object // that is passed back. var rule_index = jQuery.inArray(rule, rules);//确定rule在rules中的位置 if (rule === "custom" || rule === "funcCall") { var custom_validation_type = rules[rule_index + 1]; rule = rule + "[" + custom_validation_type + "]"; // Delete the rule from the rules array so that it doesn't try to call the // same rule over again delete(rules[rule_index]); } // Change the rule to the composite rule, if it was different from the original var alteredRule = rule; var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class"); var element_classes_array = element_classes.split(" "); // Call the original validation method. If we are dealing with dates or checkboxes, also pass the form var errorMsg; if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") { errorMsg = originalValidationMethod(form, field, rules, i, options); } else { errorMsg = originalValidationMethod(field, rules, i, options);//执行回调函数,获得错误信息 } // If the original validation method returned an error and we have a custom error message, // return the custom message instead. Otherwise return the original error message. if (errorMsg != undefined) { var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, alteredRule, options); if (custom_message) errorMsg = custom_message; } return errorMsg; }
下面就是method._custom方法
_custom: function(field, rules, i, options) { var customRule = rules[i + 1]; var rule = options.allrules[customRule]; var fn; if(!rule) { //规则没有,则提示返回 alert("jqv:custom rule not found - "+customRule); return; } if(rule["regex"]) { var ex=rule.regex;//获取相应正则 if(!ex) { alert("jqv:custom regex not found - "+customRule); return; } var pattern = new RegExp(ex);//转成正则表达式 if (!pattern.test(field.val())) return options.allrules[customRule].alertText;//匹配正则 } else if(rule["func"]) { //自定义方法验证,根据返回结果判断 fn = rule["func"]; if (typeof(fn) !== "function") { alert("jqv:custom parameter 'function' is no function - "+customRule); return; } if (!fn(field, rules, i, options)) return options.allrules[customRule].alertText; } else { alert("jqv:custom type not allowed "+customRule); return; } }
其实看到这里,我们大致明白了,核心还是调用了rule['regex']的正则表达式。其实换了思维想一下,如果我们把email直接写在switch中,那其实会有几十种,甚至是几百种情况,那一起写在switch中明显是不明智的,这个custom相当于做了个简单的带头作用,将这些更细节的验证判断,统统挂上custom的名,再进行验证。那么这个_required其实很类似
_required: function(field, rules, i, options, condRequired) { switch (field.prop("type")) {//取触发控件的类型,注意这里attr,css都不能完全取到,这里作者使用它的是prop case "text": case "password": case "textarea": case "file": case "select-one": case "select-multiple": default: var field_val = $.trim( field.val() );//去除输入的空格符 var dv_placeholder = $.trim( field.attr("data-validation-placeholder") ); var placeholder = $.trim( field.attr("placeholder") ); if ( ( !field_val ) || ( dv_placeholder && field_val == dv_placeholder ) || ( placeholder && field_val == placeholder ) ) { return options.allrules[rules[i]].alertText;//返回不填的错误信息 } break; case "radio": case "checkbox": // new validation style to only check dependent field if (condRequired) { if (!field.attr('checked')) { return options.allrules[rules[i]].alertTextCheckboxMultiple; } break; } // old validation style var form = field.closest("form, .validationEngineContainer"); var name = field.attr("name"); if (form.find("input[name='" + name + "']:checked").size() == 0) { if (form.find("input[name='" + name + "']:visible").size() == 1) return options.allrules[rules[i]].alertTextCheckboxe; else return options.allrules[rules[i]].alertTextCheckboxMultiple; } break; } }
这些方法进过验证之后,如果不满足情况,将会获得错误信息
在流程图的最后,整个插件的_showPrompt和_buildPrompt方法主要是生成页面提示
_showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) { var prompt = methods._getPrompt(field); // The ajax submit errors are not see has an error in the form, // When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time // Because no error was found befor submitting if(ajaxform) prompt = false; // Check that there is indded text if($.trim(promptText)){ if (prompt) methods._updatePrompt(field, prompt, promptText, type, ajaxed, options); else methods._buildPrompt(field, promptText, type, ajaxed, options); } }
看一下_buildPrompt方法
_buildPrompt: function(field, promptText, type, ajaxed, options) { // create the prompt var prompt = $('<div>'); prompt.addClass(methods._getClassName(field.attr("id")) + "formError"); // add a class name to identify the parent form of the prompt prompt.addClass("parentForm"+methods._getClassName(field.closest('form, .validationEngineContainer').attr("id"))); prompt.addClass("formError");//制作错误提示框,放上相应的class,这些class之前被监听过事件 switch (type) { case "pass": prompt.addClass("greenPopup"); break; case "load": prompt.addClass("blackPopup"); break; default: /* it has error */ //alert("unknown popup type:"+type); } if (ajaxed) prompt.addClass("ajaxed"); // create the prompt content var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt);//将错误信息放在div中插入prompt中 // determine position type var positionType=field.data("promptPosition") || options.promptPosition; // create the css arrow pointing at the field // note that there is no triangle on max-checkbox and radio if (options.showArrow) { var arrow = $('<div>').addClass("formErrorArrow"); //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10) if (typeof(positionType)=='string') { var pos=positionType.indexOf(":"); if(pos!=-1) positionType=positionType.substring(0,pos); } switch (positionType) {//生成小三角 case "bottomLeft": case "bottomRight": prompt.find(".formErrorContent").before(arrow); arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>'); break; case "topLeft": case "topRight": arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>'); prompt.append(arrow); break; } } // Add custom prompt class if (options.addPromptClass) prompt.addClass(options.addPromptClass); // Add custom prompt class defined in element var requiredOverride = field.attr('data-required-class'); if(requiredOverride !== undefined) { prompt.addClass(requiredOverride); } else { if(options.prettySelect) { if($('#' + field.attr('id')).next().is('select')) { var prettyOverrideClass = $('#' + field.attr('id').substr(options.usePrefix.length).substring(options.useSuffix.length)).attr('data-required-class'); if(prettyOverrideClass !== undefined) { prompt.addClass(prettyOverrideClass); } } } } prompt.css({ "opacity": 0 }); if(positionType === 'inline') { prompt.addClass("inline"); if(typeof field.attr('data-prompt-target') !== 'undefined' && $('#'+field.attr('data-prompt-target')).length > 0) { prompt.appendTo($('#'+field.attr('data-prompt-target'))); } else { field.after(prompt); } } else { field.before(prompt);//在触发控件的前面插入 } var pos = methods._calculatePosition(field, prompt, options); prompt.css({ 'position': positionType === 'inline' ? 'relative' : 'absolute', "top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize, "opacity": 0 }).data("callerField", field); if (options.autoHidePrompt) { setTimeout(function(){ prompt.animate({ "opacity": 0 },function(){ prompt.closest('.formErrorOuter').remove(); prompt.remove(); }); }, options.autoHideDelay); } return prompt.animate({ "opacity": 0.87 //动画效果 }); }
生成的小三角的实现方式比较特别。。将错误内容放入div中,将生成div插在被触发控件的前面,并且为div加上class,为什么加,在init方法中,我们已经为这类class添加了click事件,功能是点击能够删除它们。
以上完成一遍简单的验证过程。
另外,这个插件还有一个强大的功能,就是提供的ajax验证。
<input type="text" name="id" id="id" class="validate[required,ajax[ajaxUserCallPhp]]"/>
以上是页面需要添加的东西,因为关联到ajaxUserCallPhp,我们修改一下jQuery.validationEngine-en.js,找到ajaxUserCallPhp
"ajaxUserCallPhp": { "url": "../jsp/login_check.jsp",//修改成你要跳转的路径,或者你自己新写一个关联对象 // you may want to pass extra data on the ajax call "extraData": "name=eric", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This username is available", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }
这里源码是php,我这里暂时就修改为jsp页面。
String yc = (String)request.getParameter("fieldValue");
String elementId = (String)request.getParameter("fieldId");
注意后台如何获取ajax请求里的值,这里你使用抓包之类的工具就可以清楚看到url上类似拼接有fieldValue=xx&fieldId=xx,所以后台采用如此接住传过来的参数,查询数据库,判断是否有用户名,最后往ajax返回信息时
String json = "{"0":""+elementId+"","1":""+da+"","2":"yc"}";
out.println(json);
这里我简单的使用拼接的方式传递了json格式的数据,到时候,大家根据实际情况做修改。
尝试去找method里的_ajax方法,可以发现这个_ajax方法其实调用了$.ajax的方法提交请求,注意在提交之前,经过了两次for循环,主要是分解extraData,将信息组装成json格式传入data中,最后将data放入请求中根据url发送到后台。关于$.ajax,会有一个success的回调
success: function(json) { // asynchronously called on success, data is the json answer from the server var errorFieldId = json[0]; //var errorField = $($("#" + errorFieldId)[0]); var errorField = $("#"+ errorFieldId).eq(0); // make sure we found the element if (errorField.length == 1) { var status = json[1]; // read the optional msg from the server var msg = json[2]; if (!status) { // Houston we got a problem - display an red prompt options.ajaxValidCache[errorFieldId] = false; options.isError = true; // resolve the msg prompt if(msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) { msg = txt; } } }else msg = rule.alertText; if (options.showPrompts) methods._showPrompt(errorField, msg, "", true, options); } else { options.ajaxValidCache[errorFieldId] = true; // resolves the msg prompt if(msg) { //验证之后需要调用的参数方法,这个参数存在与allrules中if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) { msg = txt; } } } else msg = rule.alertTextOk; if (options.showPrompts) { // see if we should display a green prompt if (msg) methods._showPrompt(errorField, msg, "pass", true, options); else methods._closePrompt(errorField); } // If a submit form triggered this, we want to re-submit the form if (options.eventTrigger == "submit") field.closest("form").submit(); } }
这里回调函数中采用json[0],json[1],json[2]等方式取后台信息,个人觉得并不是很好,这样导致很多时候,后台发来的数据需要根据这个API接口来封装数据,有的时候会有点麻烦。感觉自定义回调比较好一点。这里我说明下这个回调里的几个参数的含义errorFieldId:表示触发ajax验证的控件的id,这个id在放送请求的时候传输到后台,并再次由后台传回前台,这个值需要有。status:举个例子,如果你输入一个用户名,如果这个用户名还没有注册,像前台传输一个status值,要非空,这样告诉前台数据库中没有这个新建的用户名。表示用户名可以注册。那第三个msg:如果你需要在ajax成功返回之后想触发其他method里的方法,可以写allrules里有的方法名即可,你也可以自己输入字符串信息,那最后提示框中将使用你自定义的信息。
以上完成了插件的ajax验证。上面的分析可能不是很全面,如果这个插件有新的功能我还没有用到,希望大家提出来,一起分享分享。
内容不多,时间刚好,以上是我的一点读码体会,如有错误,请指出,大家共通学习。