当前位置: 首页 > Web前端 > HTML5

vue表单验证100行小白自编

时间:2023-04-05 11:12:49 HTML5

vue表单验证100行小白先自己编了两份代码,一份逻辑,一份验证规则;特点:逻辑简单,代码量小,够用;如果不想看代码,直接创建这两个文件复制代码,使用方法见最下方;示例图//validator.js//引入校验规则varvalitatorRules=require('./valitator-rules.js');exportconstValidator=function(formName,rules,errors){//rules:{//name:'required|regexp_hanzi',//idCont:'regexp_I'//}this.rules=rules;//leterrors={//name:{//required:'不能为空',//regexp_hanzi:'必须beaChinesecharacter'//},//idCont:{//regexp_I:'身份证号错误',//regexp_H:'香港通行证错误',//regexp_T:'台湾通行证错误',//}//};this.error=errors;this.form=document.forms[formName];this.validatorList=[];this.init();}//初始化Validator.prototype.init=function(){for(letkeyinthis.rules){letnode=this.findNode(key);this.validatorList.push({name:key,value:'',childrenNode:node.childrenNode,parentNode:node.parentNode,borderColor:getComputedStyle(node.childrenNode).borderColor,ruleReg:this.defineRule(key),//[{rule:'hanzi',valitatorRules:fn(this.value),error:'请输入汉字'}]errors:'',})}};//动态修改校试规则Validator.prototype.changeRules=function(rules,param){letarrs=Object.keys(rules);this.rules={...this.rules,...rules}this.validatorList.forEach(val=>{if(arrs.includes(val.name)){val.ruleReg=this.defineRule(val.name)}})if(param){returnthis.validate(param)}};//校验执行者Validator.prototype.validate=function(param){leterrorList=[];returnnewPromise((resolve,reject)=>{for(letkeyinparam){this.validatorList.forEach(val=>{if(val.name==key){val.value=param[key];this.runValidator(val);}})}this.validatorList.forEach(val=>{Object.keys(param).forEach(v=>{if(val.name==v&&val.errors){errorList.push(val);}})})if(errorList.length>0){reject(this)}else{resolve()}})}//暴露出的显示错误Validator.prototype.showError=function(name){if(name){letmodule;this.validatorList.forEach(val=>{if(val.name==name){module=val;}})if(module.errors){this.createError(module);}}else{this.validatorList.forEach(val=>{if(val.errors){this.createError(val);}})}}//执行校实验工具;Validator.prototype.runValidator=function(module){letn=0;functionrun(param){if(n>=module.ruleReg.length){return}if(param.valitatorRules(module.value)){//验证通过module.errors='';n++;运行(module.ruleReg[n]);}else{module.errors=param.error;}}run(module.ruleReg[n]);if(module.errors.length==0&&module.newChildNode){this.clear(module);}}//寻找节点Validator.prototype.findNode=function(childenName){让m=this.form;letchildrenNode=form.querySelector(`input[name="${childenName}"]`)||form.querySelector(`textarea[name="${childenName}"]`);letparentNode=childrenNode.parentNode;return{childrenNode,parentNode}};//寻找验证规则Validator.prototype.defineRule=function(name){letrule=[],ruleString='';for(letkeyinthis.rules){if(name==key){ruleString=this.rules[key];}}letarr=ruleString.split('|');arr.forEach(val=>{if(valitatorRules[val]){console.log(this)rule.push({rule:val,valitatorRules:valitatorRules[val],error:this.error[name][val]})}})returnrule;}//生成错误提示Validator.prototype.createError=function(module){if(module.newChildNode){module.newChildNode.innerText=模块错误;return}letnewChildNode=document.createElement('div');newChildNode.className='_errorMessage';newChildNode.style.color='red';newChildNode.style.fontSize='12px';newChildNode.innerText=module.errors;module.newChildNode=newChildNode;module.childrenNode.style.borderColor='red';if(module.childrenNode.nextSibling){module.parentNode.insertBefore(newChildNode,module.childrenNode.nextSibling);}else{module.parentNode.appendChild(newChildNode);}}//清除错误提示Validator.prototype.clear=function(module){if(module){module.childrenNode.style.borderColor=module.borderColor;模块.parentNode.removeChild(module.newChildNode);module.newChildNode=null;}else{this.validatorList.forEach(val=>{if(val.newChildNode){val.childrenNode.style.borderColor=val.borderColor;val.parentNode.removeChild(val.newChildNode);val.newChildNode=null;}})}}下面是校验规则,简单说明一下,非空校验不单独处理,所以这里多写校验规则ifelse;//validator-rule.jsmodule。exports={hanzi:function(str){if(str){letreg=/[\u4e00-\u9fa5]/;返回reg.test(str);}别的{返回真;}},required:function(str){return!(str.length==0)},I:function(str){if(str){letreg=/i/;返回reg.test(str);}else{返回真值;}},H:function(str){if(str){letreg=/h/;返回reg.test(str);}else{返回真值;}},T:function(str){if(str){letreg=/t/;返回reg.test(str);}else{返回真值;}},}使用方法**引入验证插件import{Validator}from'@src/utils/valitator'****验证规则可自行修改添加@src/utils/valitator-rules******1.添加表单名称属性2.定义错误提示errors={name:{required:'cannotbeempty',hanzi:'必须为汉字'},idCont:{I:'身份证号码错误',H:'香港护照错误',T:'台湾通行证错误',}};3.定义验证规则rules={name:'required|hanzi',idCont:'I'}4.初始化验证实例:this.Validator=newValidator('example_form',rules,errors);5.绑定验证信息:在input中添加name属性,key与错误提示保持一致6.执行验证:将key传入被验证和价值;this.Validator.validate({[name]:this[name],}).then(()=>{}).catch((errorCb)=>{console.log(errorCb)errorCb.showError();//显示错误提示,如果只显示某个提示,则传入相应的值errorCb.showError('name')});7、动态改变验证规则,比如证书类型改变:this.Validator.changeRules({idCont:this.idType},//引入新的验证规则{idCont:this.idCont})//引入key和valueverification.then(()=>{})的验证。catch((errorCb)=>{errorCb.showError('idCont');});8:注意:每个input都要用div包裹起来,确保错误信息添加正确;this.Validator.clear();清除所有错误信息