您好,登錄后才能下訂單哦!
怎么自定義一個javascript驗證框架?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
1. 驗證框架主要采用 jquery異步對象去擴展的,也就是jquery defered 的用法,這樣去做驗證的好處是,即使某些驗證是采用ajax 方式去驗證的,結合jquery when 函數,一樣可以批量校驗. 主要代碼如下:
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(); }, /*默認的出錯處理方法*/ 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("<span validationError><label msgid='msg_" + rule +"'>" + message + "</label></span>"); } } }; //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("<span validationError><label msgid='msg_" + rule + "' errorMsgParam='"+attributeValue+"'>" + message + "</label></span>"); } }); 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("<span validationError><label msgid='msg_" + rule + "' errorMsgParam='"+attributeValue+"'>" + message + "</label></span>"); } }); 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_\-]+$/); });
對于html 頁面的驗證方式呢,采用如下方式:
<div><h2>自定義驗證框架測試</h2></div> <div> <div id="required_valid_div"> <input type="text" required minLen="3" maxLen="5"/> <p /> english:<input type="text" required english maxLen="50"/> <p /> <input type="text" required maxLen="50"/> <p /> <input type="text" url required /> <p /> email: <input type="text" email /> <p /> <select required> <option value="">請選擇</option> <option value="1">中國</option> </select> <p /> <textarea required maxLeng="500"></textarea> <p /> 自定義錯誤信息:<input type="text" url required msgid="myUrlError"/> <p /> </div> <button onclick="javascript:validatorDiv();">驗證</button> <button onclick="javascript:loadI18nCN();">Load 中文國際化</button> <button onclick="javascript:loadI18NEN();">Load English i18N</button> </div>
其中有很多自定義的屬性,比如required,maxLen, url,email 等。 當然部分與HTML5的有沖突,也不矛盾。如果不想沖突,當然可以另外定義,但要注意validation.js 要同步修改,還有i18n 國際化文件. 在這里面我自定義了一個 自定義錯誤信息,如果有msgid 屬性的會去找msgid 對應的國際化消息,否則會去找rule_加上自定義屬性的消息. 這是為了自己的項目定制的。
js 國際化的支持
var JSLocale = { msg_required: "不能為空", msg_maxLen: "最大長度{{:length}}.", msg_minLen: "最小長度{{:length}}.", msg_url: "不合法的網址", msg_email: "Email 不合法", msg_english : "只允許輸入 0-9,a-z, A-Z", myUrlError: "自定義錯誤提示:url 不合法哦", end: "" };
測試效果
看完上述內容,你們掌握怎么自定義一個javascript驗證框架的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。