100行代碼實(shí)現(xiàn)vue表單校驗(yàn)功能(小白自編)
兩個(gè)文件,一個(gè)寫邏輯,一個(gè)寫校驗(yàn)規(guī)則;
特點(diǎn):邏輯簡(jiǎn)單,代碼量少,夠用;
不想看代碼直接新建這兩個(gè)文件復(fù)制代碼,看最下面的使用方法;
示例圖片
//validator.js //引入校驗(yàn)規(guī)則 var valitatorRules = require('./valitator-rules.js'); export const Validator=function(formName,rules,errors){ // rules:{ // name:'required|regexp_hanzi', // idCont: 'regexp_I' // } this.rules = rules; // let errors = { // name:{ // required:'不能為空', // regexp_hanzi:'得是漢字' // }, // idCont:{ // regexp_I:'身份證號(hào)不對(duì)', // regexp_H:'香港通行證不對(duì)', // regexp_T:'臺(tái)灣通行證不對(duì)', // } // }; this.error = errors; this.form = document.forms[formName]; this.validatorList = []; this.init(); } //初始化 Validator.prototype.init = function(){ for (let key in this.rules){ let node = 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:'請(qǐng)輸入漢字'}] errors :'', }) } }; //動(dòng)態(tài)修改校驗(yàn)規(guī)則 Validator.prototype.changeRules = function(rules,param){ let arrs = 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){ return this.validate(param) } }; //校驗(yàn)執(zhí)行者 Validator.prototype.validate = function(param){ let errorList =[]; return new Promise((resolve,reject) => { for (let key in param){ 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() } }) } //暴露出的展示錯(cuò)誤 Validator.prototype.showError = function(name){ if(name){ let module; 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); } }) } } //執(zhí)行校驗(yàn)工具; Validator.prototype.runValidator = function(module){ let n = 0; function run(param){ if (n>=module.ruleReg.length){ return } if(param.valitatorRules(module.value)){// 驗(yàn)證通過 module.errors = ''; n++; run(module.ruleReg[n]); } else{ module.errors = param.error; } } run(module.ruleReg[n]); if(module.errors.length == 0 && module.newChildNode){ this.clear(module); } } //尋找節(jié)點(diǎn) Validator.prototype.findNode= function(childenName){ let form = this.form; let childrenNode = form.querySelector(`input[name="${childenName}"]`) || form.querySelector(`textarea[name="${childenName}"]`); let parentNode = childrenNode.parentNode; return { childrenNode, parentNode } }; //尋找驗(yàn)證規(guī)則 Validator.prototype.defineRule =function(name){ let rule = [],ruleString=''; for(let key in this.rules){ if(name == key){ ruleString = this.rules[key]; } } let arr= ruleString.split('|'); arr.forEach(val => { if(valitatorRules[val]){ console.log(this) rule.push({ rule:val, valitatorRules:valitatorRules[val], error:this.error[name][val] }) } }) return rule; } //生產(chǎn)錯(cuò)誤提示 Validator.prototype.createError = function(module){ if(module.newChildNode){ module.newChildNode.innerText = module.errors; return } let newChildNode = 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); } } //清除錯(cuò)誤提示 Validator.prototype.clear = function(module){ if(module){ module.childrenNode.style.borderColor = module.borderColor; module.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; } }) } }
下面是校驗(yàn)規(guī)則,就更簡(jiǎn)單
說明一下,非空校驗(yàn)沒有做單獨(dú)處理,所以校驗(yàn)規(guī)則這里就多寫個(gè)if else;
//validator-rule.js module.exports= { hanzi:function(str){ if(str){ let reg = /[\u4e00-\u9fa5]/; return reg.test(str); }else{ return true; } }, required:function(str){ return !(str.length == 0) }, I:function(str){ if(str){ let reg = /i/; return reg.test(str); }else{ return true; } }, H:function(str){ if(str){ let reg = /h/; return reg.test(str); }else{ return true; } }, T:function(str){ if(str){ let reg = /t/; return reg.test(str); }else{ return true; } }, }
使用方法
**引入校驗(yàn)插件 import {Validator} from '@src/utils/valitator'** **校驗(yàn)規(guī)則可自行修改添加 @src/utils/valitator-rules** **** 1.添加form name屬性<form name='example_form'></form> 2.定義錯(cuò)誤提示errors = { name:{ required:'不能為空', hanzi:'得是漢字' }, idCont:{ I:'身份證號(hào)不對(duì)', H:'香港通行證不對(duì)', T:'臺(tái)灣通行證不對(duì)', } };
3.定義校驗(yàn)規(guī)則
rules ={ name:'required|hanzi', idCont: 'I' }
4.初始化校驗(yàn)實(shí)例:this.Validator =new Validator('example_form',rules,errors);
5.綁定校驗(yàn)信息:input增加name屬性,保持和錯(cuò)誤提示key一致 <input type="text" name='name' v-model='name'>
6.執(zhí)行校驗(yàn):傳入要校驗(yàn)的key和value;
this.Validator.validate({ [name]:this[name], }).then(()=>{ }).catch((errorCb)=>{ console.log(errorCb) errorCb.showError();//展示錯(cuò)誤提示,如果只展示某個(gè)提示,傳入對(duì)應(yīng)的值errorCb.showError('name') });
7.動(dòng)態(tài)跟換校驗(yàn)規(guī)則,如證件類型更換:
this.Validator.changeRules( {idCont:this.idType},//傳入新的校驗(yàn)規(guī)則 {idCont:this.idCont})//傳入校驗(yàn)的key和value進(jìn)行校驗(yàn) .then(()=>{ }).catch((errorCb)=>{ errorCb.showError('idCont'); });
8:注意事項(xiàng):每個(gè)input要用div包起來,保證錯(cuò)誤信息位置正確添加;
this.Validator.clear();
清空所有錯(cuò)誤提示
總結(jié)
以上所述是小編給大家介紹的100行代碼vue表單校驗(yàn),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
完美解決vue 項(xiàng)目開發(fā)越久 node_modules包越大的問題
這篇文章主要介紹了vue 項(xiàng)目開發(fā)越久 node_modules包越大的問題及解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09vue項(xiàng)目打包發(fā)布后接口報(bào)405錯(cuò)誤的解決
這篇文章主要介紹了vue項(xiàng)目打包發(fā)布后接口報(bào)405錯(cuò)誤的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07Vue項(xiàng)目中禁用ESLint的幾種常見方法小結(jié)
Vue ESLint是一個(gè)基于ESLint的插件,它專門為Vue.js應(yīng)用設(shè)計(jì),用于提供JavaScript代碼風(fēng)格檢查和最佳實(shí)踐規(guī)則,Vue項(xiàng)目通常會(huì)集成ESLint,目的是為了提升代碼質(zhì)量、保持一致性和可維護(hù)性,本文介紹了Vue項(xiàng)目中禁用ESLint的幾種常見方法,需要的朋友可以參考下2024-07-07vue3集成Element-Plus之全局導(dǎo)入和按需導(dǎo)入
這篇文章主要給大家介紹了關(guān)于vue3集成Element-Plus之全局導(dǎo)入和按需導(dǎo)入的相關(guān)資料,element-plus正是element-ui針對(duì)于vue3開發(fā)的一個(gè)UI組件庫,?它的使用方式和很多其他的組件庫是一樣的,需要的朋友可以參考下2023-07-07iview table render集成switch開關(guān)的實(shí)例
下面小編就為大家分享一篇iview table render集成switch開關(guān)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03element-ui修改el-form-item樣式的詳細(xì)示例
在使用element-ui組件庫的時(shí)候經(jīng)常需要修改原有樣式,下面這篇文章主要給大家介紹了關(guān)于element-ui修改el-form-item樣式的詳細(xì)示例,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11Vue3使用vue-router如何實(shí)現(xiàn)路由跳轉(zhuǎn)與參數(shù)獲取
這篇文章主要介紹了Vue3使用vue-router如何實(shí)現(xiàn)路由跳轉(zhuǎn)與參數(shù)獲取,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Vue.js實(shí)現(xiàn)文件上傳壓縮優(yōu)化處理技巧
這篇文章主要介紹了Vue.js實(shí)現(xiàn)文件上傳壓縮優(yōu)化處理,本文給大家介紹兩種方法一種是借助canvas的封裝的文件壓縮上傳,二是使用compressorjs第三方插件實(shí)現(xiàn),本文給大家介紹的非常詳細(xì)需要的朋友可以參考下2022-11-11