1. 程式人生 > >Vue 表單校驗 vee-validate

Vue 表單校驗 vee-validate

function eal for ble this code 文字 email onf

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