您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關jQuery中輕量級表單模型驗證插件的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
JQuery插件,輕量級表單模型驗證,供大家參考,具體內容如下
var validataForm = (function(model) { model.Key = "[data-required='true']"; model.ElementList = new Array(); model.FunctionDictionary = new Dictionary(); model.ToastrCustom = function (msg) { alert(msg); } model.AddElement = function (name) { model.ElementList.push(name); }; model.AddFunction = function (name, func) { model.FunctionDictionary.add(name, func); }; model.Validata = function (formName) { for (var i = 0; i < model.ElementList.length; i++) { var thisObj = model.ElementList[i]; var str = formName + " " + thisObj + model.Key; var elements = $(str); for (var j = 0; j < elements.length; j++) { var element = elements.eq(j); var value = element.val(); var elementType = element.data().type; var func = model.FunctionDictionary.find(elementType); if (func) { var result = func(value, element); if (result.status) { var errorInfo = result.message; model.ToastrCustom(errorInfo); return; } } } } }; model.ElementList.push("input"); model.ElementList.push("select"); model.FunctionDictionary.add("required", function (value, element) { var name = element.data().name; return { status: (value === ""), message: (value === "" && name + "不能為空") }; }); return model; })(window.validataForm || {});
調用處
<form id="ValidataForm"> <input data-required="true" data-name="名稱" data-type="required" value=""> <input data-required="true" data-name="昵稱" data-type="hello"> <button id="Send">提交</button> </form> <script src="~/js/plugs/jquery-3.3.1.js"></script> <script src="~/js/Dictionary.js"></script> <script src="~/js/ValidataForm.js"></script> <script type="text/javascript"> $("#Send").click(function () { validataForm.Validata("#ValidataForm"); }); </script>
Dictionary這個對象是抄一個博主的
代碼附上,內置鏈接
/* https://www.cnblogs.com/baiyangyuanzi/p/6689554.html */ /*字典 Dictionary類*/ function Dictionary() { this.add = add; this.datastore = new Array(); this.find = find; this.remove = remove; this.count = count; this.clear = clear; } function add(key, value) { this.datastore[key] = value; } function find(key) { return this.datastore[key]; } function remove(key) { delete this.datastore[key]; } function count() { /*var ss = Object.keys(this.datastore).length; console.log("ssss "+ss); return Object.keys(this.datastore).length;*/ /**/ var n = 0; for (var key in Object.keys(this.datastore)) { ++n; } return n; } function clear() { for (var key in this.datastore) { delete this.datastore[key]; } }
關于“jQuery中輕量級表單模型驗證插件的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。