如何在vue中實(shí)現(xiàn)一個(gè)表單校驗(yàn)功能?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

//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)證通過(guò)
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)單
說(shuō)明一下,非空校驗(yàn)沒(méi)有做單獨(dú)處理,所以校驗(yàn)規(guī)則這里就多寫(xiě)個(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ī)則,如證件類(lèi)型更換:
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包起來(lái),保證錯(cuò)誤信息位置正確添加;
this.Validator.clear();清空所有錯(cuò)誤提示
關(guān)于如何在vue中實(shí)現(xiàn)一個(gè)表單校驗(yàn)功能問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計(jì)公司行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線(xiàn),公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。
當(dāng)前名稱(chēng):如何在vue中實(shí)現(xiàn)一個(gè)表單校驗(yàn)功能-創(chuàng)新互聯(lián)
文章分享:http://www.chinadenli.net/article24/docsce.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開(kāi)發(fā)、網(wǎng)站維護(hù)、外貿(mào)網(wǎng)站建設(shè)、云服務(wù)器、品牌網(wǎng)站設(shè)計(jì)、微信公眾號(hào)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容