怎么自定義一個(gè)javascript驗(yàn)證框架?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
創(chuàng)新互聯(lián)公司是一家朝氣蓬勃的網(wǎng)站建設(shè)公司。公司專(zhuān)注于為企業(yè)提供信息化建設(shè)解決方案。從事網(wǎng)站開(kāi)發(fā),網(wǎng)站制作,網(wǎng)站設(shè)計(jì),網(wǎng)站模板,微信公眾號(hào)開(kāi)發(fā),軟件開(kāi)發(fā),小程序設(shè)計(jì),10年建站對(duì)成都攪拌罐車(chē)等多個(gè)行業(yè),擁有多年的網(wǎng)站維護(hù)經(jīng)驗(yàn)。
1. 驗(yàn)證框架主要采用 jquery異步對(duì)象去擴(kuò)展的,也就是jquery defered 的用法,這樣去做驗(yàn)證的好處是,即使某些驗(yàn)證是采用ajax 方式去驗(yàn)證的,結(jié)合jquery when 函數(shù),一樣可以批量校驗(yàn). 主要代碼如下:
function Validator(errorHandle){ this.errorHandle = errorHandle; this.elements = ["input","select","textarea"]; } Validator.prototype = { contructor : Validator, rules : {}, addRules : function(ruleName, validFunction, errorFunction){ this.rules[ruleName] = { validFunction : validFunction, errorFunction : errorFunction }; }, eventFunction : function(item){ var self = this; $(item).die().live("blur", function(){ self.validateItem(item); }); }, bindingEvent : function(divId){ var self = this; self.elements.forEach(function(element){ $("#" + divId).find(element).each(function(i, item){ self.eventFunction(item); }); }); }, validateDiv : function(divId){ var dtdList = [], self = this; self.elements.forEach(function(element){ $("#" + divId).find(element).each(function(i, item){ dtdList.push( self.validateItem(item) ); }); }); self.elements.forEach(function(element){ if ($("#" + divId).find(element).length == 0){ var deferred = $.Deferred(); deferred.resolve(); dtdList.push(deferred); } }); return $.when.apply(null, dtdList).fail(function(){ if(self.errorHandle) { self.errorHandle.call(null, divId); } }); }, validateItem : function(d){ var self = this; var ruleList = []; for(var r in this.rules){ if( $(d).is("[" + r + "]") ){ ruleList.push(r); } } var dtd = $.Deferred(); var checked = function(){ if ( ruleList.length >= 1 ){ var ok = self.validate(d, ruleList[0]); ok.done(function(){ if(ruleList.length >= 2){ self.validate(d, ruleList[1]); } ruleList.shift(); checked(); }).fail(function(){ dtd.reject(); }); } else { dtd.resolve(); } ; //dtd.resolve(); //return dtd; }; checked(); return dtd; }, validate : function(d, rule){ var value = $(d).val(), attributeValue = $(d).attr(rule), f = this.rules[rule].validFunction, self = this; var ok = f.call(null, d, value, attributeValue); return ok.fail(function(item){ if($(item).siblings("[validationError]").length != 0 ){ $(item).siblings("[validationError]").remove(); } if(self.rules[rule].errorFunction){ self.rules[rule].errorFunction(d, rule); }else { self.showErrorMessage(d, rule); } }).done(function(item){ if($(item).siblings("[validationError]").length != 0 ){ $(item).siblings("[validationError]").remove(); } }); }, validationByRegx : function(d, value, regx){ var dtd = $.Deferred(), ok = regx.test(value); if(ok || $.trim(value) === ""){ dtd.resolve(d); } else { dtd.reject(d); } return dtd.promise(); }, /*默認(rèn)的出錯(cuò)處理方法*/ showErrorMessage : function(item,rule){ var msgInfo = getJSLocale( $(item).attr("msgid") ); var ruleInfo = getJSLocale( "msg_" + rule ); if($(item).siblings("span").find("[msgid='msg_"+ rule +"']").length == 0){ var message = msgInfo || ruleInfo; $(item).parent().append(""); } } }; //add default rule Validator.prototype.addRules("required", function(d, value, attributeValue){ var dtd = $.Deferred(); var ok = !($.trim(value) == "" || value == null); if(ok){ dtd.resolve(d); } else { dtd.reject(d); } return dtd.promise(); }); Validator.prototype.addRules("maxLen", function(d, value, attributeValue){ var dtd = $.Deferred(); var ok = (value.length <= attributeValue); if(ok){ dtd.resolve(d); } else { dtd.reject(d, attributeValue); } return dtd.promise(); }, function(d, rule){ if($(d).siblings("span").find("[msgid='msg_" + rule + "']").length == 0){ var attributeValue = $(d).attr(rule); var msgInfo = getJSLocale( $(d).attr("msgid"), {length:attributeValue} ); var ruleInfo = getJSLocale( "msg_" + rule, {length:attributeValue} ); var message = msgInfo || ruleInfo; $(d).parent().append(""); } }); Validator.prototype.addRules("minLen", function(d, value, attributeValue){ var dtd = $.Deferred(); var ok = (value.length >= attributeValue); if(ok){ dtd.resolve(d); } else { dtd.reject(d, attributeValue); } return dtd.promise(); }, function(d, rule){ if($(d).siblings("span").find("[msgid='msg_" + rule + "']").length == 0){ var attributeValue = $(d).attr(rule); var msgInfo = getJSLocale( $(d).attr("msgid"), {length:attributeValue} ); var ruleInfo = getJSLocale( "msg_" + rule, {length:attributeValue} ); var message = msgInfo || ruleInfo; $(d).parent().append(""); } }); Validator.prototype.addRules("url", function(d, value, attributeValue){ return Validator.prototype.validationByRegx(d, value, /^(((ht|f)tp(s?))\:\/\/)[a-zA-Z0-9]+\.[a-zA-Z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/i); }); Validator.prototype.addRules("email", function(d, value, attributeValue){ return Validator.prototype.validationByRegx(d, value, /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/); }); Validator.prototype.addRules("english", function(d, value, attributeValue){ return Validator.prototype.validationByRegx(d, value, /^[a-zA-Z0-9_\-]+$/); });
對(duì)于html 頁(yè)面的驗(yàn)證方式呢,采用如下方式:
自定義驗(yàn)證框架測(cè)試
english: email: 自定義錯(cuò)誤信息:
其中有很多自定義的屬性,比如required,maxLen, url,email 等。 當(dāng)然部分與HTML5的有沖突,也不矛盾。如果不想沖突,當(dāng)然可以另外定義,但要注意validation.js 要同步修改,還有i18n 國(guó)際化文件. 在這里面我自定義了一個(gè) 自定義錯(cuò)誤信息,如果有msgid 屬性的會(huì)去找msgid 對(duì)應(yīng)的國(guó)際化消息,否則會(huì)去找rule_加上自定義屬性的消息. 這是為了自己的項(xiàng)目定制的。
js 國(guó)際化的支持
var JSLocale = { msg_required: "不能為空", msg_maxLen: "最大長(zhǎng)度{{:length}}.", msg_minLen: "最小長(zhǎng)度{{:length}}.", msg_url: "不合法的網(wǎng)址", msg_email: "Email 不合法", msg_english : "只允許輸入 0-9,a-z, A-Z", myUrlError: "自定義錯(cuò)誤提示:url 不合法哦", end: "" };
測(cè)試效果
看完上述內(nèi)容,你們掌握怎么自定義一個(gè)javascript驗(yàn)證框架的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!