vee-validate 使用记录

创建validator/index.js

import Vue from 'vue'
import { ValidationProvider, ValidationObserver, extend, localize } from 'vee-validate'
import * as rules from 'vee-validate/dist/rules'
import zh_CN from 'vee-validate/dist/locale/zh_CN.json'

Object.keys(rules).forEach(rule => {
  extend(rule, {
    ...rules[rule],
    message: zh_CN[rule]
  })
})

localize('zh_CN', zh_CN)

Vue.component('ValidationObserver', ValidationObserver)
Vue.component('ValidationProvider', ValidationProvider)

并在项目的main.js中 引入:import ‘@/validator’,即可全局使用该组件

<template>
  <validation-provider v-if="flagIf" v-show="flagShow" :name="title" :style="isRequired ? 'color: #FF5257' : ''" :rules="Object.assign({required: required}, custRules)" v-slot="{ errors, validate }">
    <md-field-item :disabled="disabled" :solid="solid" :title="isRequired ? '* ' + title : title" v-model="content" :content="content" :arrow="arrow" :placeholder="placeholder"  @click="onClick">
    </md-field-item>
    <div class="errorMsg" v-show="errors.length > 0">{{errors[0]}}</div>
  </validation-provider>
</template>

在自定义组件中使用,如上代码,其中custRules是根据自身需求写的计算属性,在调用该组件时由父组件传入的rules计算来。

computed: {
    custRules() {
      if (this.rules && this.rules[this.name]) {
        return this.rules[this.name]
      }
      return {}
    },
    isRequired() {
      if (this.required) {
        return true
      }
      if (this.rules && this.rules[this.name] && this.rules[this.name]['required']) {
        return true
      }
      return false
    }
  },

如果需要自定义验证规则,那么可以在validator/index.js或需要用到的页面上增加extend(都是全局的,所有页面可用),即可在rule中使用
如下:

import { extend } from 'vee-validate'
extend('minmax', {
  validate(value, { min, max }) {
    return value.length >= min && value.length <= max
  },
  params: ['min', 'max'],
  message: '{_field_} 的长度应该在 {min} 在 {max} 之间'
})

//以下是data中的数据
{
rules: {
    CarCode: {
       min: 1,
       max: 10
     },
     ClientMobile: {
       digits: 11
     },
     ClientName: {
       minmax: [3, 6]
     }
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值