Vue 一个简单的表单验证指令

第一步:

  写一个全局的插件  globle.js  并添加个Vue指令  v-validate  , 并在其中定义验证规则,如下,添加了输入字数限制和仅支持输入数字校验

 1 function install(Vue, options) {
 2   // v-max
 3   Vue.directive('validate', function (el, arg) {
 4     const validate = {
 5       init: function (params) {
 6         params.maxlength && this.maxlength(params.maxlength)
 7         params.number && this.onlyNumber()
 8       },
 9       maxlength: function (max) {
10         el.addEventListener('input', function () {
11           el.value.length > max && (el.value = el.value.slice(0, max))
12         })
13       },
14       onlyNumber: function () {
15         let func = function () {
16           el.value = el.value.replace(/[^\d]/g,'')
17         }
18         el.addEventListener('keydown', func)
19         el.addEventListener('blur', func)
20         el.addEventListener('change', func)
21         el.addEventListener('input', func)
22       },
23 
24     }
25     validate.init(arg.value)
26   })
27 }
28 
29 export default install

第二步:

       mian.js 中引入并  use 

1 import Vue from 'vue'
2 import App from './App.vue'
3 import Globle from './plugin/globle'
4 Vue.config.productionTip = false
5 Vue.use(Globle)
6 new Vue({
7   render: h => h(App),
8 }).$mount('#app')

第三步:

  在页面中使用,可以看出校验规则是在  v-validate  指令的参数中传入的,需要用到什么指令就添加对应的参数

<input type="text" v-validate="{maxlength: 11}" placeholder="限制成11位"/>
<input type="text" v-validate="{number: true}" placeholder="限制成纯数字">
<input type="text" v-validate="{number: true, maxlength: 11}" placeholder="限制成11位的纯数字">

 

以上!

 

posted @ 2019-06-11 14:58  blackbentel  阅读(1516)  评论(0编辑  收藏  举报