//数据类型 var frameui_validateform = window.frameui_validateform || {}; frameui_validateform.validateidx =1; var validatedatatypes = {}; //验证指定 vue.directive('validate', { //初始化或组件中的key改变时会触发 bind: function (el, binding, vnode, oldvnode) { var vue = vnode.context; var config = binding.value; var validateformitems = vue.validateformitems; if (validateformitems == undefined) { validateformitems = []; vue.validateformitems = validateformitems; } config.el = el; var idx = frameui_validateform.validateidx; var oldidx = -1; if (binding.oldvalue && binding.oldvalue.idx) { oldidx = binding.oldvalue.idx; } else { oldidx = binding.value.idx; } if (oldidx == undefined) { oldidx = -1; } if (oldidx >= 0) { config.idx = oldidx;//序号 config.binded = true; var arrayindex = validateformitems.findindex(function (item) { return item.idx == oldidx}); if (arrayindex >= 0) { validateformitems[arrayindex] = config; } } else { config.binded = true; config.idx = idx;//序号 validateformitems.push(config); } frameui_validateform.validateidx++; }, unbind: function (el, binding, vnode, oldvnode) { //v-if或key改变会触发 var idx = -1; if (binding.oldvalue != undefined) { idx = binding.oldvalue.idx; } else { idx=binding.value.idx; } if (idx == undefined) { return; } var vue = vnode.context; var validateformitems = vue.validateformitems; var itemidx = validateformitems.findindex(function (item) { return item.idx == idx }); if (itemidx >= 0) { var config = binding.value; config.binded = false; validateformitems[itemidx] = config; } }, update: function (el, binding, vnode, oldvnode) { var vue = vnode.context; var validateformitems = vue.validateformitems; var idx = binding.oldvalue.idx; var config = binding.value; config.el = el; config.idx = idx;//序号 config.binded = true; if (idx>=0) { var arrayindex = validateformitems.findindex(function (item) { return item.idx == idx }); { validateformitems[arrayindex] = config; } } } }); //vue全局验证 vue.mixin({ methods: { //验证 validateform: function (thisoptions, validateindex) { var vue = this; var defaultoptions = { showallerror: true, datatypes: {},//这里声明的是局部数据类型,也可以通过全局validatedatatypes在外部声明 tipsstyle: 1, //0,:alert, 1:msg 2,表单前后 ,3:all errorclass: "validate-error", tipserroraddclass: "validate-tips-error", alltipsboxtarget: ".validate-all-tips-box", beforecheck: null, beforesubmit: null }; var defaultoptions = extend({}, defaultoptions, thisoptions); vue.validateformconfig = defaultoptions; var showallerror = defaultoptions.showallerror; var datatypes = defaultoptions.datatypes; var tipsstyle = defaultoptions.tipsstyle; if (tipsstyle != 2) { showallerror = false; } var beforecheck = defaultoptions.beforecheck; var beforesubmit = defaultoptions.beforesubmit; var errorclass = defaultoptions.errorclass; //验证出错后表单添加的样式 var tipserrorclass = defaultoptions.tipserroraddclass; //错误提示添加的样式,tipsstyle为2时有效 var alltipsboxtarget = defaultoptions.alltipsboxtarget; //form第一行或最后一行提示信息的ul样式,tipsstyle为3时有效 var validateformitems = vue.validateformitems; //console.log(validateformitems) if (validateformitems == undefined) { return true; } //开始验证 var startvalidate = function () { var canexecute = true; if (typeof (beforecheck) == "string") { if (beforecheck != "") { canexecute = eval(beforeexecute); } } else if (typeof (beforecheck) == "function") { canexecute = beforecheck(); } if (typeof canexecute != "boolean") { canexecute = true; } var validaresult; if (canexecute) { validaresult = validating(); //开始遍历验证 } else { return false; } if (!validaresult) { return false; } if (typeof (beforesubmit) == "string") { if (beforesubmit != "") { canexecute = eval(beforesubmit); } } else if (typeof (beforesubmit) == "function") { canexecute = beforesubmit(); } if (typeof canexecute != "boolean") { canexecute = true; } return canexecute; }; //遍历所有数据,进行验证 var validating = function () { var errorindex = 0; //获取到错误的序号 var validateresult = true; var $alltipsboxtarget = null; if (alltipsboxtarget) { document.queryselector(alltipsboxtarget); } if ($alltipsboxtarget != null) { $alltipsboxtarget.innerhtml = ""; } for (var i = 0; i < validateformitems.length; i++) { var validateconfig = validateformitems[i]; if (!validateconfig.binded) { continue; } var result = validateitem(validateconfig, errorindex); if (!result) { errorindex++; validateresult = validateresult && result; } if (!showallerror) { if (result == false) { return false; //如果不需要显示所有错误信息,则加return false跳出each循环 } } } return validateresult; }; var validateitem = function (validateconfig, errorindex) { var defaultconfig = { datatype: "*", focustarget: "", tipstarget: "", regexp: "", getlengthbybyte:false,minlength:0,maxlength: 0, nullmsg: "值不能为空!", errormsg: "填写错误!", autotruncated: true, maxlengtherrormsg: "不能超过个{0}字符!", minlengtherrormsg: "最少输入个{0}字符!", ignore: false, ignoreempty: false,compare: null, checkurl: "", checkdata: null, checkerror: "", additionals: "", beforeexecute: null, execute: null }; validateconfig = extend(defaultconfig, validateconfig); var $el = validateconfig.el; var validatetarget = validateconfig.validatetarget; var ignore = validateconfig.ignore; var focustarget = validateconfig.focustarget; var $focustarget = null; if (focustarget) { $focustarget = document.queryselector(focustarget); } else { $focustarget = $el.queryselector(".el-input__inner"); } if (ignore) { return true;//继续下一个循环 } var result = validatedatatype(validateconfig); if ($focustarget != null) { if (showallerror) { if (errorindex == 0) { if (result) { $focustarget.classlist.remove(errorclass); } else { $focustarget.focus(); $focustarget.classlist.add(errorclass); } } } else { if (result) { $focustarget.classlist.remove(errorclass); } else { $focustarget.focus(); $focustarget.classlist.add(errorclass); } } } return result; }; //验证数据类型,在validating中调用,表单的的input和 propertychange事件会同时触发 var validatedatatype = function (validateconfig) { var datatype = validateconfig.datatype.trim(); var regexpstr = validateconfig.regexp; var getlengthbybyte = validateconfig.getlengthbybyte; var minlength = validateconfig.minlength; var maxlength = validateconfig.maxlength; var minlengtherrormsg = validateconfig.minlengtherrormsg; var maxlengtherrormsg = validateconfig.maxlengtherrormsg; var autotruncated = validateconfig.autotruncated; //超过最大长度是否自动截断 var nullmsg = validateconfig.nullmsg; var errormsg = validateconfig.errormsg; var ignoreempty = validateconfig.ignoreempty; var compare = validateconfig.compare; var checkurl = validateconfig.checkurl; var checkerror = validateconfig.checkerror; var checkadditionals = validateconfig.additionals; var tipstarget = validateconfig.tipstarget; //表单提示信息的span容器样式,没有定义则动态添加,tipsstyle为2时有效 var validatetarget = validateconfig.validatetarget; var beforeexecute = validateconfig.beforeexecute; var execute = validateconfig.execute; var result = false; var gets = validateconfig.data; var resulttype; if (gets === undefined || gets === null) { gets = ""; } var nomorevalidate = false;//表示是否继续后面的验证,对表单对比,远程ajax if (!validateconfig.hasownproperty("data")) { nomorevalidate = true; result = true; } if (!nomorevalidate) { if (gets == "" && ignoreempty == true) //先进行非空忽略验证 { nomorevalidate = true; result = true; } } //执行前 if (!nomorevalidate && !isnullorempty(beforeexecute)) { if (typeof (beforeexecute) == "string") { if (beforeexecute != "") { result = eval(beforeexecute); } } else if (typeof (beforeexecute) == "function") { result = beforeexecute(validateconfig); } resulttype = typeof (result); if (resulttype != "boolean") { nomorevalidate = true; } else if (!result) { nomorevalidate = true; } } //接下来进行最小长度验证 if (!nomorevalidate) { if (minlength > 0) { var currentlength = gets.strlength(getlengthbybyte); if (currentlength == 0) { result = nullmsg; } else if (currentlength < minlength) { result = minlengtherrormsg.replace("{0}", minlength); } else { result = true; } resulttype = typeof (result); if (resulttype != "boolean") { nomorevalidate = true; } else if (!result) { nomorevalidate = true; } } } //接下来进行最大长度截取 if (!nomorevalidate && typeof (gets) == "string") { var currentlength = gets.strlength(getlengthbybyte); if (maxlength > 0 && currentlength > maxlength) { if (autotruncated) { //自动截断 var $input = validateconfig.el.queryselector(".el-input__inner"); if ($input != null) { $input.value = gets.left(maxlength,getlengthbybyte); $input.dispatchevent(new event("input"));//触发v-model $input.dispatchevent(new event("change"));//触发v-model } } else { result = maxlengtherrormsg.replace("{0}", maxlength); nomorevalidate = true; } } } //然后再进行数据类型验证 if (!nomorevalidate) { if (regexpstr != "")//有正则优先用正则匹配 { var reg = new regexp(regexpstr); result = reg.test(gets); } else { switch (datatype) { case "": case "*": result = validatedatatypes.defaultdatatype(gets, validateconfig); break; default: var datatypefun = datatypes[datatype]; //先检测datatypes内部是否有定义,也可以用datatypes.hasownproperty(datatype)判断 if (datatypefun == undefined) //如果找不到则到validatedatatypes中去找 { datatypefun = validatedatatypes[datatype]; } if (typeof (datatypefun) != "function") { alert(datatype + "数据类型未定义"); return false; } else { result = datatypefun(gets, validateconfig);//只能返回字符串,true或flase,字符串默认为false; if (typeof (result) == "string") { errormsg = result; result = false; } } break; } } } resulttype = typeof (result); if (resulttype != "boolean") { nomorevalidate = true; } else if (!result) { nomorevalidate = true; } ///然后再进行比较验证 if (!nomorevalidate) { if (compare != null)//和其他值对别 { if (gets != compare) { result = errormsg; } } } resulttype = typeof (result); if (resulttype != "boolean") { nomorevalidate = true; } else if (!result) { nomorevalidate = true; } //进行execute验证 if (!nomorevalidate) { if (typeof (execute) == "string") { if (execute != "") { result = eval(execute); } } else if (typeof (execute) == "function") { result = execute(validateconfig); } } resulttype = typeof (result); if (resulttype != "boolean") { nomorevalidate = true; } else if (!result) { nomorevalidate = true; } //进行远程验证 if (!nomorevalidate) { if (checkurl != "" && gets != "")//远程验证 { var serverdata = { data: gets }; var checkresult = ajax({ type: "post", url: checkurl, data: serverdata, async: false });//同步方法 checkresult = jsonparse(checkresult); if (checkresult.state == 1) { } else if (checkresult.state == 0) { if (checkerror != "") { result = checkerror; } else { result = checkresult.msg; } } else { result = checkresult.msg; } } } resulttype = typeof (result); //每次验证后都需要重新获取 if (resulttype == "boolean") { } else if (resulttype == "string") //返回字符串则表示不成功 { nullmsg = errormsg = result; result = false; } else { result = false; nullmsg = errormsg = "填写错误(数据类型必须返回bool或字符串)!"; } showtips(result, gets, nullmsg, errormsg, validateconfig); return result; }; //显示提示信息 var showtips = function (result, gets, nullmsg, errormsg, validateconfig) { var tipsmsg = ""; if (gets.tostring() == "") { tipsmsg = nullmsg; } else { tipsmsg = errormsg } switch (tipsstyle.tostring()) { case "1": tipsstyle1(result, tipsmsg, validateconfig); //依赖layer.js break; case "2": //html显示 tipsstyle2(result, tipsmsg, validateconfig); break; case "3": // tipsstyle3(result, tipsmsg, validateconfig); break; default: defaulttipsstyle(result, tipsmsg, validateconfig); break; } }; //默认风格,采用alert var defaulttipsstyle = function (result, tipsmsg, validateconfig) { if (result) { return; } //console.log(validateconfig.el); alert(tipsmsg); }; var tipsstyle1 = function (result, tipsmsg, validateconfig) { if (result) { return; } //console.log(validateconfig.el); vue.$message({ message: tipsmsg, type: "warning", showclose: true }); }; //容器内部显示 var tipsstyle2 = function (result, tipsmsg, validateconfig) { var tipstarget = validateconfig.tipstarget; var $item = validateconfig.el; var $tipbox = null; if (tipstarget) { $tipbox = document.queryselector(tipstarget); } if ($tipbox != null) { var defaulttext = $tipbox.getattribute("data-default-text"); if (defaulttext == undefined) { defaulttext = $tipbox.innerhtml; $tipbox.setattribute("data-default-text", defaulttext); } if (result) { $tipbox.innerhtml = defaulttext $tipbox.classlist.remove(tipserrorclass); } else { $tipbox.innerhtml = tipsmsg; $tipbox.classlist.add(tipserrorclass); } showallerror = true; } else { if (!result) { console.log(validateconfig.el); ui.msg({ content: tipsmsg, type: "warning" }); showallerror = false; } } }; //顶部显示 var tipsstyle3 = function (result, tipsmsg) { var $tipsbox = document.queryselector(alltipsboxtarget); if ($tipsbox != null) { if (result) { $tipsbox.innerhtml = ""; //避免页面跳动 return; } //console.log(validateconfig.el); $tipsbox.innerhtml = tipsmsg; } }; if (validateindex == undefined) { return startvalidate(); } else { if (tipsstyle == 2) { return validateitem(validateformitems[validateindex], 0); //弹出提示不需要单个验证! } } }, } }) //默认验证 validatedatatypes.defaultdatatype = function (gets, itemconfig) { if (array.isarray(gets)) { if (gets.length == 0) { gets = ""; } } if (gets == null || gets == undefined) { return false; } if (gets.tostring().trim() == "") { return false; } return true; } //匹配字符串 validatedatatypes.string = function (gets, itemconfig) { if (isstr(gets)) { return true } else { return false; } } //匹配数值型,默认最小值是-2147483647,默认最大值是2147483647,支持小数 validatedatatypes.numeric = function (gets, itemconfig) { var defaultoptions = { max: 2147483647, min: -2147483647 }; defaultoptions = extend({}, defaultoptions, itemconfig); var max = defaultoptions.max; var min = defaultoptions.min; if (!isnumeric(gets)) { return false } if (typeof (gets) == "string"){ gets = parsefloat(gets); } if (gets > max) { return false; } else if (gets < min) { return false; } return true; } //匹配货币类型 validatedatatypes.money = function (gets, itemconfig) { var reg = /^([\u0024\u00a2\u00a3\u00a4\u20ac\u00a5\u20b1\20b9\uffe5]\s*)(\d+,?)+\.?\d*\s*$/; return reg.test(gets) } //匹配中文 validatedatatypes.chinese = function (gets, itemconfig) { var reg = /^[\u4e00-\u9fa5]+$/; return reg.test(gets) } validatedatatypes.email = function (gets, itemconfig) { if (isemail(gets)) { return true; } else { return false; } } validatedatatypes.mobile = function (gets, itemconfig) { if (ismobile(gets)) { return true; } else { return false; } } validatedatatypes.editor = function (gets, itemconfig) { var editorid = itemconfig.el.getattribute("name"); if (gets == "") { if (editorid != null) { var editorobj = ue.geteditor(editorid); editorobj.focus(true); } return false; } else { return true; } } validatedatatypes.username = function (gets, itemconfig) { if (isnullorempty(gets)) { return "请填写用户名!"; } else if (isnumeric(gets)) { return "用户名不能为纯数字!"; } var len = gets.strlength(true); if (len < 4) { return "用户名最少由4个字符组成,中文占两个字符!"; } else if (len > 16) { return "用户名不能超过16个字符,中文占两个字符!"; } if (!isusername(gets)) { return "用户名仅支持中英文、数字和下划线!"; } return true; } validatedatatypes.password = function (gets, itemconfig) { if (isnullorempty(gets)) { return "请填写密码!"; } if (includechinese(gets)) { return "密码不能包含中文字符!"; } var len = gets.strlength(); if (len < 6) { return "密码最少由6个字符组成!"; } else if (len > 20) { return "密码不能超过20个字符!"; } return true; } validatedatatypes.datetime = function (gets, itemconfig) { if (isdatetime(gets)) { return true; } else { return false; } } validatedatatypes.date = function (gets, itemconfig) { if (isdate(gets)) { return true; } else { return false; } } validatedatatypes.file = function (gets, itemconfig) { if (gets.indexof(".") > 0 && gets.length >= 4 && gets.indexof(".") < (gets.length - 1)) { return true; } else { return false } } //匹配身份证 validatedatatypes.idcard = function (gets, itemconfig) { var wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1];// 加权因子; var validecode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2];// 身份证验证位值,10代表x; if (gets.length == 15) { return isvaliditybrithby15idcard(gets); } else if (gets.length == 18) { var a_idcard = gets.split("");// 得到身份证数组 if (isvaliditybrithby18idcard(gets) && istruevalidatecodeby18idcard(a_idcard)) { return true; } return false; } return false; function istruevalidatecodeby18idcard(a_idcard) { var sum = 0; // 声明加权求和变量 if (a_idcard[17].tolowercase() == 'x') { a_idcard[17] = 10;// 将最后位为x的验证码替换为10方便后续操作 } for (var i = 0; i < 17; i++) { sum += wi[i] * a_idcard[i];// 加权求和 } valcodeposition = sum % 11;// 得到验证码所位置 if (a_idcard[17] == validecode[valcodeposition]) { return true; } return false; } function isvaliditybrithby18idcard(idcard18) { var year = idcard18.substring(6, 10); var month = idcard18.substring(10, 12); var day = idcard18.substring(12, 14); var temp_date = new date(year, parsefloat(month) - 1, parsefloat(day)); // 这里用getfullyear()获取年份,避免千年虫问题 if (temp_date.getfullyear() != parsefloat(year) || temp_date.getmonth() != parsefloat(month) - 1 || temp_date.getdate() != parsefloat(day)) { return false; } return true; } function isvaliditybrithby15idcard(idcard15) { var year = idcard15.substring(6, 8); var month = idcard15.substring(8, 10); var day = idcard15.substring(10, 12); var temp_date = new date(year, parsefloat(month) - 1, parsefloat(day)); // 对于老身份证中的你年龄则不需考虑千年虫问题而使用getyear()方法 if (temp_date.getyear() != parsefloat(year) || temp_date.getmonth() != parsefloat(month) - 1 || temp_date.getdate() != parsefloat(day)) { return false; } return true; } } validatedatatypes.table = function (gets, itemconfig) { gets = gets.tostring().trim(); if (islstr(gets)) { return checkkey(gets); } else { return "表名只能由字母,数字和下划线组成,而且首字母必须是英文!"; } } validatedatatypes.field = function (gets, itemconfig) { gets = gets.tostring().trim(); if (islstr(gets)) { return checkkey(gets); } else { return "字段只能由字母,数字组成,而且首字母必须是英文!"; } } function checkkey(str) { str = str.tolowercase(); var keys = new array("in", "as", "currentpage", "page", "pagesize", "order", "sa", "dbo", "system", "index", "by", "select", "from", "table", "tableid", "table_", "field_", "top", "asc", "desc", "count", "sum", "link", "update", "insert", "to", "values", "where", "delete", "join", "charge", "guid", "parentguid", "id"); if (keys.findindex(function (item) { item == str }) >= 0) { return "对不起," + str + "为表名或字段名的屏蔽词,请重写设置!" } else { return true; } }