vue表单验证插件

vee-validate is a plugin for Vue.js that allows you to validate input fields and display errors.

Installation

npm

npm install vee-validate --save

Getting Started

In your script entry point:

import Vue from 'vue';
import VeeValidate from 'vee-validate';

Vue.use(VeeValidate);

Now you are all setup to use the plugin.

Usage

Just apply the v-validate directive on your input and pass a string value which is a list of validations separated by a pipe. For example, we will use the required and the email validators:

<input v-validate="'required|email'" type="text" name="email">

Alternatively you can pass an object for more flexibility:

<input v-validate="{ required: true, email: true, regex: /[0-9]+/ }" type="text" name="email">

Now every time the input changes, the validator will run the list of validations from left to right, populating the errors helper object whenever an input fails validation.

实例

demo

  • validate.js :创建一个文件,将表单验证的代码单独抽离出来
  • main.js :vue 主文件入口,引入validate.js
  • form.vue :表单组件
// src/util/validate.js
import Vue from 'vue'

// 1. 表单验证依赖文件,并且引入的是支持中文错误提示的文件。
import VeeValidate, {Validator} from 'vee-validate'
import zh_CN from 'vee-validate/dist/locale/zh_CN';
Validator.addLocale(zh_CN);

// 2. 中文错误提示的配置
const validateConfig = {
    locale: 'zh_CN'
};
Vue.use(VeeValidate, validateConfig);

// 3. 自定义表单验证的提示语 
const dictionary = {
   zh_CN: {
      messages: {  // message: 提示语
        required: ( field )=> field + "不能为空"
      },
      attributes:{  // attributes: filed
        username: '用户名',
         account: '帐号',
        password: '密码',
       cpassword: '确认密码',
           phone: '手机号',
            code: '验证码'
      }
  }
};
Validator.updateDictionary(dictionary);

// 4. 扩展自定义的验证
Validator.extend('phone', {
  messages: {
    zh_CN: field => field + '输入有误',
  },
  validate: value => {
    return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
  }
});

Validator.extend('string', {
  messages: {
    zh_CN: field => '请输入5~15位数字、字母或符号',
  },
  validate: value => {
    return /^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{5,15}$/.test(value)
  }
});

form.vue

<div class="form-items">
  <input class="input-text" type="text" v-model.trim="value.phone" v-validate="'required|phone'" name="phone" :placeholder="placeholder.phone">
  <div v-show="errors.has('phone')" class="tooltip-verify">{{ errors.first('phone') }}</div>
</div>
this.$validator.validateAll(['phone','code']).then((result) => { 
  // code
})

this.$validator.validateAll().then((result) => {
  // code
})

常见问题

iview与vee-validate

  • 问题描述:The computed property "fields" is already defined in data.
  • 解决方案:
    const validateConfig = {
      fieldsBagName: 'vee-fields', // 默认为 fields
    };
    

results matching ""

    No results matching ""