码迷,mamicode.com
首页 > 其他好文 > 详细

Vue 表单校验 vee-validate

时间:2018-08-25 17:25:09      阅读:555      评论:0      收藏:0      [点我收藏+]

标签:方便   exclude   ace   code   def   号码   hub   install   blank   

gitHub 地址:https://github.com/baianat/vee-validate

官网API 地址:https://baianat.github.io/vee-validate/api/

配置

先下载到项目 npm install vee-validate --save

封装一个自定义指令,方便后面使用

import {Validator, install as VeeValidate} from ‘vee-validate‘;
import {required, min, max, excluded, included} from ‘vee-validate/dist/rules.esm.js‘;
import {messages, rules} from ‘@/util‘;

import ‘@/assets/style/validation.sass‘;

export default function install(Vue) {
    Validator.extend(‘required‘, required);
    Validator.extend(‘min‘, min);
    Validator.extend(‘max‘, max);
    Validator.extend(‘excluded‘, excluded);
    Validator.extend(‘included‘, included);

    Vue.use(VeeValidate, {
        locale: ‘cn‘,
        dictionary: {
            cn: {messages}
        },
        classes: [‘invalid‘],
        fieldsBagName: ‘xfields‘
    });

    for (let key in rules) {
        key && Validator.extend(key, rules[key]);
    }
}

更多配置参考 https://baianat.github.io/vee-validate/configuration.html

util.js 下面放一些自定义的规则,列如

import {included} from ‘vee-validate/dist/rules.esm.js‘;

export const messages = {
    required: field => `${field}为必填项`,
    max: (field, len) => `${field}长度不可多于${len}`,
    min: (field, len) => `${field}长度最多${len}`
};

export const rules = {
    phone: {
        getMessage: () => ‘手机号码格式不正确‘,
        validate: value => /^(?=\d{11}$)^1(?:3\d|4[57]|5[^4\D]|66|7[^249\D]|8\d|9[89])\d{8}$/.test(value)
    },
    email: {
        getMessage: field => `${field}格式不正确`,
        validate: email
    },
    phoneExcluded: {
        getMessage: () => ‘手机号码格式不正确‘,
        validate: (value, args) => {
            return included(value, args) || /^(?=\d{11}$)^1(?:3\d|4[57]|5[^4\D]|66|7[^249\D]|8\d|9[89])\d{8}$/.test(value) // eslint-disable-line
        }
    },
}

在vue中使用方法,例如

<el-input
    v-model="form.successTextPrompt"
    v-validate="{required: true, max: 20}"
    data-vv-as="文字提示"
    data-vv-name="successTextPrompt"
    placeholder="请输入"
/>
<span class="error-msg" v-show="errors.has(‘successTextPrompt‘)">{{ errors.first(‘successTextPrompt‘) }}</span>
methods: {
  submit() {
    this.$validator.validateAll().then(valid => {
          if (valid) {
               // 校验成功
          }          
      }
  }
}

 

Vue 表单校验 vee-validate

标签:方便   exclude   ace   code   def   号码   hub   install   blank   

原文地址:https://www.cnblogs.com/shenjp/p/9534560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!