JQuery插件,轻量级表单模型验证(续 二)
好不容易,有心思,那就把没做完的JQuery轻量级表单验证做完吧
之前做到了空参数验证的,现在增加带参数的验证。
附上html
<form id="ValidataForm"> <input type="number" data-required="true" data-name="数字范围" data-type="required|Range:10,15" value=""> <button id="Send">提交</button> </form>
一个很常见的输入框,输入框是数字类型,必填,范围是10到15之间
之前框架的实现修改了一下,原来eq是JQuery对象,JavaScript自带的Array是没有eq方法的,改了一通,代码附上
var validateForm = (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.Validate = 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; if (elementType.indexOf("|") > -1) { var splitStrs = elementType.split("|"); for (var index in splitStrs) { var splitStr = splitStrs[index]; var find = model.FunctionDictionary.contains(splitStr); if (find) { if (splitStr.indexOf(":") > -1) { var params = splitStr.split(":"); var func = model.FunctionDictionary.find(params[0]); if (func) { var result = func(value, element, params[1]); if (result.status) { var errorInfo = result.message; model.ToastrCustom(errorInfo); return; } } } else { var func = model.FunctionDictionary.find(splitStr); if (func) { var result = func(value, element); if (result.status) { var errorInfo = result.message; model.ToastrCustom(errorInfo); return; } } } } } } else { 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.validateForm || {});
扩展了一个方法
validateForm.AddFunction("Range", function (value, element, params) { var name = element.data().name; try { var items = params.split(","); if (items.length != 2) { return { status: false, message: name + " 验证格式不对" }; } var min = new Number(items[0]); var max = new Number(items[1]); var valueNum = new Number(value); var check = (min < max) && (min < valueNum && valueNum < max); return { status: check, message: (check && name + " 范围不对") }; } catch (error) { console.log(error); return { status: false, message: error.message }; } });