如何在vue中實現一個表單校驗功能?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
創新互聯建站是一家企業級云計算解決方案提供商,超15年IDC數據中心運營經驗。主營GPU顯卡服務器,站群服務器,內蒙古服務器托管,海外高防服務器,機柜大帶寬租用·托管,動態撥號VPS,海外云手機,海外云服務器,海外服務器租用托管等。
//validator.js
//引入校驗規則
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:'身份證號不對',
// regexp_H:'香港通行證不對',
// regexp_T:'臺灣通行證不對',
// }
// };
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:'請輸入漢字'}]
errors :'',
})
}
};
//動態修改校驗規則
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)
}
};
//校驗執行者
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()
}
})
}
//暴露出的展示錯誤
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);
}
})
}
}
//執行校驗工具;
Validator.prototype.runValidator = function(module){
let n = 0;
function run(param){
if (n>=module.ruleReg.length){
return
}
if(param.valitatorRules(module.value)){// 驗證通過
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);
}
}
//尋找節點
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
}
};
//尋找驗證規則
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;
}
//生產錯誤提示
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);
}
}
//清除錯誤提示
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;
}
})
}
}
下面是校驗規則,就更簡單
說明一下,非空校驗沒有做單獨處理,所以校驗規則這里就多寫個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;
}
},
}
使用方法
**引入校驗插件 import {Validator} from '@src/utils/valitator'**
**校驗規則可自行修改添加 @src/utils/valitator-rules**
****
1.添加form name屬性<form name='example_form'></form>
2.定義錯誤提示errors = {
name:{
required:'不能為空',
hanzi:'得是漢字'
},
idCont:{
I:'身份證號不對',
H:'香港通行證不對',
T:'臺灣通行證不對',
}
};
3.定義校驗規則
rules ={
name:'required|hanzi',
idCont: 'I'
}
4.初始化校驗實例:this.Validator =new Validator('example_form',rules,errors);
5.綁定校驗信息:input增加name屬性,保持和錯誤提示key一致 <input type="text" name='name' v-model='name'>
6.執行校驗:傳入要校驗的key和value;
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和value進行校驗
.then(()=>{
}).catch((errorCb)=>{
errorCb.showError('idCont');
});
8:注意事項:每個input要用div包起來,保證錯誤信息位置正確添加;
this.Validator.clear();
清空所有錯誤提示
關于如何在vue中實現一個表單校驗功能問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創新互聯行業資訊頻道了解更多相關知識。
網頁題目:如何在vue中實現一個表單校驗功能
分享URL:http://vcdvsql.cn/article14/poogde.html
成都網站建設公司_創新互聯,為您提供小程序開發、搜索引擎優化、動態網站、域名注冊、云服務器、用戶體驗
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯