服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - vue实现表单数据验证的实例代码

vue实现表单数据验证的实例代码

2021-09-13 17:24Maple_feng JavaScript

这篇文章主要介绍了vue实现表单数据验证的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  • 为el-form表单添加:rules
  • 在data中定义规则
  • 将定义的规则绑定在el-form-item

代码如下:

?
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
<!--登录表单区域-->
  <el-form :model="loginForm" label-width="0px" class="login_form" :rules="loginFormRules">
  <!--用户名-->
   <el-form-item prop="username">
    <el-input v-model="loginForm.username" prefix-icon="el-icon-user"></el-input>
  </el-form-item>
  <!--密码-->
  <el-form-item prop="password">
    <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" type="password"></el-input>
  </el-form-item>
  <!--按钮区域-->
  <el-form-item class="btns">
    <el-button type="primary">登录</el-button>
    <el-button type="info">重置</el-button>
  </el-form-item>
  </el-form>
<script>
 export default{
 data(){
  return {
  //登录表单数据绑定对象
  loginForm:{
   username:'',
   password:''
  },
  //表单验证规则
  loginFormRules:{
   //验证用户名是否合法
   username:[
   { required: true, message: '请输入用户名', trigger: 'blur' },
   { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
   ],
   //验证密码是否合法
   password:[
   { required: true, message: '请输入密码', trigger: 'blur' },
   { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
   ]
  }
  }
 }
 }
</script>

PS:下面看下vue 自定义指令input表单的数据验证的代码

一、代码

?
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
<template>
  <div class="check" >
    <h3>{{msg}}</h3>
    <div class="input">
      <input type="text" v-input v-focus><span>{{msg1}}</span>
    </div>
    <div class="input">
      <input type="text" v-input v-required><span>{{msg2}}</span>
    </div>
    <div class="input">
      <!-- required:true/false 表示这个是必填项 -->
      <input type="text" v-input v-checked="{required:true,}"><span>{{msg3}}</span>
    </div>
    <div class="input">
      <!-- <input type="text" v-input v-validate="'required|email|phone|min(5)|max(15)|minlength(6)|maxlength(12)|regex(/^[0-9]*$/)'">
      required 验证是否是必填项
      email 验证是否是邮箱
      phone 验证是否是电话号码
      min(5) 验证最小值
      max(3) 验证最大值
      minlength(6) 验证最小长度
      maxlength(12) 验证最大长度
      regex(/^[0-9]*$/) 进行正则验证
      -->
      <input type="text" v-input
          v-validate="'required|min(5)|max(15)|minlength(6)|maxlength(12)|regex(/^[0-9]*$/)'" placeholder="多选验证">
    </div>
    <div class="input">
      <!--
      验证必须是数字:/^[0-9]*$/
      验证由26个英文字母组成的字符串:/^[A-Za-z]+$/
      验证手机号: /^[1][3,4,5,7,8][0-9]{9}$/;
      验证邮箱:/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
      -->
      <input type="text" v-input v-validate="'required|phone'" placeholder="验证手机号码">
    </div>
    <div class="input">
      <input type="text" v-input v-validate="'required|email'" placeholder="验证邮箱">
    </div>
  </div>
</template>
 
<script>
  export default {
    name: 'check',
    data() {
      return {
        msg: '指令',
        tipsBorderColor: 'red',
        msg1: '最简单的指令',
        msg2: '验证不能为空的指令',
        msg3: '进行正则验证',
        tipsMsg: '',
      }
    },
 
    directives: {
      // 修饰input框的指令
      input: {
        // 当被绑定的元素插入到DOM上的时候
        inserted: function (el) {
          el.style.width = "300px";
          el.style.height = "35px";
          el.style.lineHeight = "35px";
          el.style.background = "#ddd";
          el.style.fontSize = "16px";
          el.style.border = "1px solid #eee";
          el.style.textIndent = "5px";
          el.style.textIndent = "8px";
          el.style.borderRadius = "5px";
        }
      },
      // input框默认选中的指令
      focus: {
        inserted: function (el) {
          el.focus();
        }
      },
      // 不能为空的指令
      required: {
        inserted: function (el) {
          el.addEventListener('blur', function () {
            if (el.value == '' || el.value == null) {
              el.style.border = "1px solid red";
              console.log('我不能为空');
            }
 
          })
        }
      },
      // 验证指令
      checked: {
        inserted: function (el) {
          return el
        }
      },
      // 验证
      validate: {
        inserted: function (el, validateStr) {
          // 将验证规则拆分为验证数组
          let validateRuleArr = validateStr.value.split("|");
          // 监听失去焦点的时候
          el.addEventListener('blur', function () {
            //失去焦点进行验证
            checkedfun();
          });
 
          // 循环进行验证
          function checkedfun() {
            for (var i = 0; i < validateRuleArr.length; ++i) {
              let requiredRegex = /^required$/; // 判断设置了required
              let emailRegex = /^email$/; // 判断设置了email
              let phoneRegex = /^phone$/; // 判断设置了 phone
              let minRegex = /min\(/; //判断设置了min 最小值
              let maxRegex = /max\(/; //判断设置了max 最大值
              let minlengthRegex = /minlength\(/; //判断设置了 minlength 最大长度
              let maxlengthRegex = /maxlength\(/; //判断设置了 maxlength 最大长度
              let regexRegex = /regex\(/;
              // 判断设置了required
              if (requiredRegex.test(validateRuleArr[i])) {
                if (!required()) {
                  break;
                } else {
                  removeTips();
                }
 
              }
 
              // 判断设置了email
              if (emailRegex.test(validateRuleArr[i])) {
                if (!email()) {
                  break;
                } else {
                  removeTips();
                }
 
              }
 
              // 判断设置了 phone
              if (phoneRegex.test(validateRuleArr[i])) {
                if (!phone()) {
                  break;
                } else {
                  removeTips();
                }
 
              }
 
              // 判断是否设置了最小值
              if (minRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }
 
              }
 
              // 判断是否设置了最大值
              if (maxRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }
 
              }
 
              // 判断设置了最小长度
              if (minlengthRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }
 
              }
 
              // 判断设置了最大长度
              if (maxlengthRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }
 
              }
 
              // 判断测试正则表达式
              if (regexRegex.test(validateRuleArr[i])) {
                if (!eval(validateRuleArr[i])) {
                  break;
                } else {
                  removeTips();
                }
 
              }
 
            }
 
          }
 
          // 验证是否是必填项
          function required() {
            if (el.value == '' || el.value == null) {
              // console.log("不能为空");
              tipMsg("不能为空");
              return false;
            }
 
            return true;
          }
 
          // 验证是否是邮箱
          function email() {
            let emailRule = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
            if (!emailRule.test(el.value)) {
              tipMsg("请输入正确的邮箱地址");
              return false;
            }
 
            return true;
          }
 
          // 验证是否是手机号码
          function phone() {
            let phoneRule = /^[1][3,4,5,7,8][0-9]{9}$/;
            if (!phoneRule.test(el.value)) {
              tipMsg("请输入正确的手机号码");
              return false;
            }
 
            return true;
          }
 
          // 最小值验证
          function min(num) {
            if (el.value < num) {
              tipMsg("最小值不能小于" + num);
              //console.log('最小值不能小于'+num);
              return false;
            }
 
            return true;
          }
 
          // 最大值验证
          function max(num) {
            if (el.value > num) {
              tipMsg("最大值不能大于" + num);
              //console.log('最大值不能大于'+num);
              return false;
            }
 
            return true;
          }
 
          // 最小长度验证
          function minlength(length) {
            if (el.value.length < length) {
              //console.log('最小长度不能小于'+length);
              tipMsg("最小长度不能小于" + length);
              return false;
            }
 
            return true;
          }
 
          // 最大长度进行验证
          function maxlength(length) {
            if (el.value.length > length) {
              //console.log('最大长度不能大于'+length);
              tipMsg("最大长度不能大于" + length);
              return false;
            }
            return true;
          }
 
          // 进行正则表达式的验证
          function regex(rules) {
            if (!rules.test(el.value)) {
              tipMsg("请输入正确的格式");
              return false;
            }
            return true;
          }
 
          // 添加提示信息
          function tipMsg(msg) {
            removeTips();
            let tipsDiv = document.createElement('div');
            let curDate = Date.parse(new Date());
            tipsDiv.innerText = msg;
            tipsDiv.className = "tipsDiv";
            tipsDiv.id = curDate;
            tipsDiv.style.position = "absolute";
            tipsDiv.style.top = el.offsetTop + 45 + 'px';
            tipsDiv.style.left = el.offsetLeft + 'px';
            document.body.appendChild(tipsDiv);
            //setTimeout(function(){
            // document.getElementById(curDate).remove();
            //},2000);
          }
 
          // 移除提示信息
          function removeTips() {
            if (document.getElementsByClassName('tipsDiv')[0]) {
              document.getElementsByClassName('tipsDiv')[0].remove();
            }
 
          }
        },
      }
    }
  }
</script>
 
<style>
 
  .input {
    padding-bottom: 20px;
    float: left;
    clear: both;
    margin-left: 500px;
    display: block;
 
  }
 
  .check input {
    width: 300px;
    height: 35px;
    outline: none;
    background: #ddd;
  }
 
  .check span {
    padding-left: 20px;
  }
 
  .tipsDiv {
    height: 27px;
    line-height: 25px;
    border: 1px solid #333;
    background: #333;
    padding: 0px 5px;
    border-radius: 4px;
    color: #fff;
    font-size: 16px;
  }
 
  .tipsDiv:before {
    content: '';
    display: block;
    border-width: 0 5px 8px;
    border-style: solid;
    border-color: transparent transparent #000;
    position: absolute;
    top: -9px;
    left: 6px;
  }
</style>

总结

到此这篇关于vue实现表单数据验证的实例代码的文章就介绍到这了,更多相关vue 表单数据验证内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/angelyan/p/11065554.html

延伸 · 阅读

精彩推荐