两个文件,一个写逻辑,一个写校验规则;

特点:逻辑简单,代码量少,够用;

不想看代码直接新建这两个文件复制代码,看最下面的使用方法;

示例图片

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//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;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//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;
  }
},
}

使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
**引入校验插件 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.定义校验规则

1
2
3
4
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;

1
2
3
4
5
6
7
8
this.Validator.validate({
   [name]:this[name],
 }).then(()=>{
 
 }).catch((errorCb)=>{
   console.log(errorCb)
   errorCb.showError();//展示错误提示,如果只展示某个提示,传入对应的值errorCb.showError('name')
 });

    7.动态跟换校验规则,如证件类型更换:

1
2
3
4
5
6
7
8
this.Validator.changeRules(
  {idCont:this.idType},//传入新的校验规则
  {idCont:this.idCont})//传入校验的key和value进行校验
  .then(()=>{
 
  }).catch((errorCb)=>{
  errorCb.showError('idCont');
});

    8:注意事项:每个input要用div包起来,保证错误信息位置正确添加;

    this.Validator.clear();清空所有错误提示

总结

以上所述是小编给大家介绍的100行代码vue表单校验,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

posted on   ygunoil  阅读(509)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示