由于只是初步测试通过,还有很多功能未去完善,比如单选和多选项等的验证
1.由于是纯js的,所以首先是获取dom对象的js
(function (_this) { _window = _this ? _this.window : window; _window.thsoft = _window.thsoft || {}; _window.thsoft.dom = _window.thsoft.dom || {}; _window.thsoft.dom.tools = { /* parentNode:目标节点,要添加子几点的对象 */ appendElement: function (parentNode, newNode) { if (typeof parentNode != ‘object‘) { alert("The target[parentNode] is not an HTMLElement!"); return false; } if (typeof newNode != ‘object‘) { alert("The target[newNode] is not an HTMLElement!"); return false; } parentNode.appendChild(newNode); return newNode; }, appendText: function (node, text) { if (typeof node != ‘object‘) { alert("The target[parentNode] is not an HTMLElement!"); return false; } if (node.tagName == ‘INPUT‘) node.value += text; else node.innerHTML += text; return true; }, /* parentNode:目标节点,要添加子几点的对象 newNode:要添加的对象 */ removeElement: function (parentNode, newNode) { if (typeof parentNode != ‘object‘) { alert("The target[parentNode] is not an HTMLElement!"); return false; } if (typeof newNode != ‘object‘) { alert("The target[newNode] is not an HTMLElement!"); return false; } parentNode.removeChild(newNode); return true; }, /* tagName:要创建的节点名称 attrObj:要为新节点添加的属性 {‘$width‘:‘100px‘}$: 表示标签的style属性 不带$表示标签属性; */ createElement: function (tagName, attrObj) { if (tagName === "" || tagName === undefined) { alert("tagName is undefined!"); return false; } var newNode = document.createElement(tagName); thsoft.dom.tools.setAttribute(newNode, attrObj); return newNode; }, setAttribute: function (node, attrObj) { var cssText = ""; for (var item in attrObj) { if (item.indexOf(‘$‘) != -1) { cssText += item.replace(‘$‘,‘‘) + ":" + attrObj[item] + ";"; continue; } //此处需要解决兼容性 if (item === ‘event‘) { thsoft.tools.event.addEvent(node, attrObj[item].name, attrObj[item].handle); } else if (item === ‘innerHTML‘) node.innerHTML = attrObj[item]; else node.setAttribute(item, attrObj[item]); } node.style.cssText = cssText; node.setAttribute(‘style‘, cssText); return node; }, //设置对象样式 css: function (node, attrObj) { for (var item in attrObj) node.style[item.replace(‘$‘, ‘‘)] = attrObj[item]; }, ///调用方法 id:#id class and attribute tagName[attrName=attrValue] getNode: function (attrName) { ///优先Id获取 var cursor = attrName.indexOf(‘#‘); if (cursor !== -1) return _window.document.getElementById(attrName.replace(‘#‘, ‘‘)); //class获取 方式如:input[class=cname] var cursors = attrName.replace(‘[‘, ‘,‘).replace(‘]‘, ‘,‘).replace(‘=‘, ‘,‘).split(‘,‘); if (cursors.length !== 4) return null; //tn:tagName cn:className cv:class value var tn = cursors[0], cn = cursors[1], cv = cursors[2]; nodes = _window.document.getElementsByTagName(tn); n = []; for (var i = 0; i < nodes.length; i++) if (nodes[i].attributes[cn].value === cv) n.push(nodes[i]); return n; } }; })(this);
2.dom元素辅助插件写好后就开始写验证插件
(function (_this) { _window = _this ? _this.window : window; _window.thsoft = _window.thsoft || {}; _window.thsoft.validator = { objects: { form: {}, formElements: {}, tipPanels: {}, tipIcons: {}, submitBtns: [], callback: null, tipPanelParms: { $width: ‘200px‘, $position: ‘absolute‘, $background: ‘white‘, $border: ‘1px solid #007acc‘, tabIndex: 1, $padding: ‘5px‘ } }, config: { isForm: true, erroColor: ‘#ffa9a9‘, tipType: { info: { icon: "url(‘Script/thsoft.validator/icon/info.png‘) no-repeat center", foreColor: ‘#007acc‘ }, erro: { icon: "url(‘Script/thsoft.validator/icon/erro.png‘) no-repeat center", foreColor: ‘red‘ }, pass: { icon: "url(‘Script/thsoft.validator/icon/pass.png‘) no-repeat center", foreColor: ‘green‘ } } }, /*验证规则*/ rule: { num: /^[0-9]*$/, name: function (v) { if (v == 1) return true; } }, //todo 验证错误的提示 tip: { num: ‘您输入的不是数字!‘, pass: ‘验证通过!‘, nullMsg: ‘此项为必填项!‘, ignorMsg: ‘此项可为空!‘, erroMsg: ‘验证失败!请确认输入的值是否正确!‘ }, /* todo: parms:参数 可配置 提交按钮 验证规则rule,验证提示消息 配置提交按钮 支持tagNam[type=typevalue] .btn #btn 方式 毁掉函数:callback 调用方式: thsoft.validator.init({ submitBtn: ‘.btn‘, rule: { num: /^[0-9]*$/ }, Msgs: { num: ‘您输入的不是数字!‘ }, callback:function(){ } }); */ init: function (parms) { //todo 初始化 for (var items in parms) { if (items === ‘submitBtn‘) thsoft.validator.objects.submitBtns.push(thsoft.dom.tools.getNode(parms[items])); else if (items === ‘rule‘) for (var item in parms[items]) thsoft.validator.rule[item] = parms[items][item]; else if (items === ‘Msgs‘) for (var i in parms[items]) thsoft.validator.tip[item] = parms[items][item]; else if (items === ‘callback‘) thsoft.validator.objects.callback = parms[items]; } form = thsoft.dom.tools.getNode(‘form[verify=true]‘); if ((form == null || form.length == 0) && !thsoft.validator.config.isForm) { alert("未找到任何form,请检查是否有form表单或者是否有在form上配置verify=‘true’属性!"); return false; } form = form[0]; thsoft.validator.objects.form = form; formElements = []; for (var i = 0; i < form.length; i++) { eml = form.elements[i]; //处理提交按钮 if (eml.attributes[‘type‘] !== undefined && eml.attributes[‘type‘].value === ‘submit‘) thsoft.validator.objects.submitBtns.push(eml); //todo 屏蔽掉button if ((eml.attributes[‘type‘] !== undefined && eml.attributes[‘type‘].value === ‘button‘) || eml.attributes[‘rule‘] === undefined || eml.attributes[‘rule‘].value === ‘‘) continue; //todo 增加验证方法 eml.onblur = function () { thsoft.validator.verify(this); }; eml.onfocus = function () { thsoft.validator.showTip(this); }; eml.onkeyup = function () { thsoft.validator.verify(this) }; //todo 给对象创建提示 thsoft.validator.newTip(eml); formElements.push(eml); } //设置提交按钮事件 if (thsoft.validator.objects.submitBtns.length > 0) for (var i = 0; i < thsoft.validator.objects.submitBtns.length; i++) { thsoft.validator.objects.submitBtns[i].onclick = function () { return thsoft.validator.submit(); }; } thsoft.validator.objects.formElements = formElements; }, //todo 验证方法 verify: function (el) { //todo 取出ignor属性 判断是否可为空 ignor = (el.attributes[‘ignor‘] !== undefined && el.attributes[‘ignor‘].value === ‘true‘); //todo 取出value value = el.value; //todo 不是必填项 可为空 if (value === ‘‘ && !ignor) { //todo 空值处理 thsoft.validator.addErro(el, ‘null‘); return false; } rule = el.attributes[‘rule‘].value; //todo 判断定义的规则是否存在 if (thsoft.validator.rule.hasOwnProperty(rule)) //todo 存在就取出规则 rule = thsoft.validator.rule[el.attributes[‘rule‘].value]; //todo 没有在规则里面定义 也可以将规则写在rule属性里面 //todo 如果rule定义的是函数 if (rule instanceof Function) { if (!rule(value)) { //todo 验证不通过处理 thsoft.validator.addErro(el, rule); return false; } } //todo 规则为正则表达式的处理 else { var reg = new RegExp(rule); if (!reg.test(value)) { thsoft.validator.addErro(el, rule); return false; } } thsoft.validator.removeErro(el); return true; }, newTip: function (el) { //todo 根据当前时间生存ID 用于验证对象去取提示框的标记 var currDate = new Date(); var guid = "T" + (Math.random() / Math.random()) + currDate.getSeconds() + currDate.getMilliseconds(); el.setAttribute(‘traget‘, guid); el.traget = guid; var position = thsoft.validator.getPosition(el); //todo 增加提示图标开始 图片使用16px var tipIcon = thsoft.dom.tools.createElement(‘div‘, { traget: guid, $width: ‘20px‘, $height: ‘20px‘, $position: ‘absolute‘, $background: thsoft.validator.config.tipType.info.icon, $padding: ‘0px‘, $left: (position.x + el.offsetWidth) + ‘px‘, $top: position.y + ‘px‘ }); thsoft.dom.tools.appendElement(_window.document.body, tipIcon); //将tipIcon 增加到thsoft.validator.objects.tipPanels中 便于验证时改变图标 thsoft.validator.objects.tipIcons[guid] = tipIcon; //todo 设置提示图标悬停事件 tipIcon.onmouseover = function (e) { thsoft.validator.showTip(this); }; //todo 设置提示图标鼠标离开事件 tipIcon.onmouseout = function (e) { //todo 隐藏提示框处理 thsoft.validator.clerTip(this); }; //todo 增加提示图标结束 //todo 设置提示框的参数 if (typeof parms === ‘object‘) for (var parm in parms) thsoft.validator.objects.tipPanelParms[parm] = parms[parm]; //在此设置参数防止在外边调用时修改 thsoft.validator.objects.tipPanelParms[‘$font-size‘] = ‘13px‘; thsoft.validator.objects.tipPanelParms[‘id‘] = guid; thsoft.validator.objects.tipPanelParms[‘$left‘] = ((position.x + el.offsetWidth) + tipIcon.offsetWidth + 2) + ‘px‘; thsoft.validator.objects.tipPanelParms[‘$top‘] = position.y + ‘px‘; thsoft.validator.objects.tipPanelParms[‘$color‘] = thsoft.validator.config.tipType.info.foreColor; //设置提示消息 tipMsg = el.attributes[‘tipmsg‘]; if (tipMsg !== undefined) tipMsg = tipMsg.value; else { ignor = (el.attributes[‘ignor‘] !== undefined && el.attributes[‘ignor‘].value === ‘true‘); if (ignor) tipMsg = thsoft.validator.tip.ignorMsg; else tipMsg = ""; } thsoft.validator.objects.tipPanelParms[‘innerHTML‘] = tipMsg; //todo 创建时默认隐藏 thsoft.validator.objects.tipPanelParms[‘$display‘] = ‘none‘; //todo 设置提示框参数结束 //todo 创建提示信息框开始 var tipPanel = thsoft.dom.tools.createElement(‘div‘, thsoft.validator.objects.tipPanelParms); thsoft.dom.tools.appendElement(_window.document.body, tipPanel); thsoft.validator.objects.tipPanels[guid] = tipPanel; //todo 创建提示信息框结束 }, //todo 增加提示 showTip: function (el, msg) { if (msg !== undefined && msg !== ‘‘) thsoft.validator.objects.tipPanels[el.attributes[‘traget‘].value].innerHTML = msg; if (el.attributes[‘traget‘] === undefined) return; thsoft.validator.objects.tipPanels[el.attributes[‘traget‘].value].style.display = ‘block‘; }, //todo 清除提示 clerTip: function (el) { thsoft.validator.objects.tipPanels[el.attributes[‘traget‘].value].style.display = ‘none‘; }, addErro: function (el, rule) { el.pass = false; erroMsg = ‘‘; //todo 验证不通过处理 //如果违反必填项约定 if (rule === ‘null‘) { //取出空值提示消息 erroMsg = el.attributes[‘nullmsg‘]; if (erroMsg !== undefined) erroMsg = el.attributes[‘nullmsg‘].value; else erroMsg = thsoft.validator.tip.nullMsg; } else { //取出erromsg节点属性 erroMsg = el.attributes[‘erromsg‘]; //如果有配置erromsg属性 则取出值 if (erroMsg !== undefined) { erroMsg = el.attributes[‘erromsg‘].value; } else if (thsoft.validator.tip.hasOwnProperty(rule)) { //如果没有则根据rule节点属性去tip对象去去 erroMsg = thsoft.validator.tip[rule]; } else { erroMsg = thsoft.validator.tip.erroMsg; } } //todo 设置当前元素的提示样式 if (el.backColor == undefined && el.backColor !== thsoft.validator.config.erroColor) el.backColor = el.style.backgroundColor; el.style.backgroundColor = thsoft.validator.config.erroColor; thsoft.validator.objects.tipPanels[el.attributes[‘traget‘].value].style.color = thsoft.validator.config.tipType.erro.foreColor; thsoft.validator.objects.tipIcons[el.attributes[‘traget‘].value].style.background = thsoft.validator.config.tipType.erro.icon; thsoft.validator.showTip(el, erroMsg); }, removeErro: function (el) { //todo 提交时判断元素的el.pass 不等于undefined 或者false 就验证通过 el.pass = true; if (el.backColor !== undefined) el.style.backgroundColor = el.backColor; thsoft.validator.objects.tipIcons[el.attributes[‘traget‘].value].style.background = thsoft.validator.config.tipType.pass.icon; thsoft.validator.objects.tipPanels[el.attributes[‘traget‘].value].style.color = thsoft.validator.config.tipType.pass.foreColor; thsoft.validator.objects.tipPanels[el.attributes[‘traget‘].value].innerHTML = thsoft.validator.tip.pass; thsoft.validator.clerTip(el); }, submit: function () { var formElements = thsoft.validator.objects.formElements; pass = true; for (var i = 0; i < formElements.length; i++) { if (!thsoft.validator.verify(formElements[i])) { pass = false; return false; } } if (thsoft.validator.objects.callback !== null) thsoft.validator.objects.callback(); else return true; }, //获取元素相对于浏览器的位置 getPosition: function (el) { _x = 0, _y = 0; while (true) { //todo 由于 获取td tr的offsetTop 值都是一样 所以要过滤处理 if (el.tagName == "TR") { el = el.parentNode; continue; } _x += el.offsetLeft; _y += el.offsetTop; if (el.tagName == ‘BODY‘) break; el = el.parentNode; } return { x: _x, y: _y }; } }; })(this);
3.下面是测试用的html
<html> <head> <title> New Document </title> <script src="Script/thsoft.tools/thsoft.dom.tools.js"></script> <script src="Script/thsoft.validator/thsoft.validator.tools.js"></script> <script type="text/javascript"> window.onload = function () { thsoft.validator.init({ submitBtn: ‘#submitBtn‘, rule: { num: /^[0-9]*$/, email: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/ }, Msgs: { num: ‘您输入的不是数字ya!‘, email:‘你输入的邮箱格式不正确!‘ }, callback: function () { alert(‘已提交!‘); } }); }; </script> </head> <body style="padding:0px; margin:0px; height:2000px"> <!--<iframe src="index2.html" style="margin-top:300px;margin-left:300px; width:900px"></iframe>--> <form id="myForm" verify="true"> <div>index2</div> <input type="button" value="显示视频" style=" float:right" onclick="thsoft.video.tools.open()" /> <input id="id0" rule="num" ignor="true" erromsg="你输入的地址长度不对!" style="height:100px"> <table cellpadding="0" cellspacing="0" border="1" width="600" style=" margin:0px auto"> <tbody> <tr> <td>姓名</td> <td> <div><input style="width:200px;" id="cx" rule="name" tipmsg="请输入姓名!" erromsg="你输入的姓名格式不对!"></div> </td> </tr> <tr> <td>年龄</td> <td> <input id="id1" rule="num" tipmsg="请输入年龄!" erromsg="你输入的不是数字!" nullmsg="年龄不能为空!"></td> </tr> <tr> <td>Email</td> <td> <div><input id="id2" tipmsg="请输入邮箱!" rule="email" nullmsg="邮箱不能为空!" ignor=" false"></div></td> </tr> <tr> <td>地址</td> <td> <div><input id="id3" rule="num" ignor="true"></div></td> </tr> </tbody> </table> <input type="submit" value="submit提交" /><input id="submitBtn" type="button" value="其他事件提交" /> </form> </body> </html>
另附上需要用到的图标:
如果需要 请适当修改js中的图片路径 以便正常使用
时间: 2024-10-12 21:44:18