1. 程式人生 > >vue爬坑——vee-validate的使用

vue爬坑——vee-validate的使用

vue爬坑——vee-validate的使用

1、npm安裝vee-validate

npm install vee-validate --save

安裝時要注意安裝的版本,不同的版本使用的方式不一樣,這裡我安裝的是”^2.0.0-rc.26”。
具體版本的使用見官網:vee-validate官網

2、main.js裡引用vee-validate外掛

import Vue from 'vue'
import VeeValidate,{ Validator } from 'vee-validate'
import zh_CN from 'vee-validate/dist/locale/zh_CN'
Vue.use(VeeValidate);

3、vee-validate提示語漢化

//提示語漢化
Validator.locale ==="en" ? "zh_CN" : "en";
Validator.localize(Validator.locale,{
    messages: zh_CN.messages,
    attributes:{
        loginName:'登入名',
        loginPassword:'密碼'
    }
});

4、驗證方法擴充套件

Validator.extend('phone', {
    getMessage
: (field, [args]) => `請輸入正確的手機號碼`, validate: (value, [args]) =>{ const reg = /^((13|14|15|17|18)[0-9]{1}\d{8})$/; return reg.test(value) } });

5、元件中使用

<form class="form" autocomplete="off" @submit.prevent="formSubmit">
  <div class="form-item">
    <input type="text"
placeholder="請輸入手機號" v-model="loginName" name="loginName" id="loginName" v-validate.initial="'required|phone'" maxlength="11" :class="{'valid-error':errors.has('loginName')}"/> </div> <div class="form-item"> <input type="password" placeholder="請輸入密碼" v-model="loginPassword" maxlength="18" name="loginPassword" id="loginPassword" :class="{'valid-error':errors.has('loginPassword')}" v-validate.initial="'required|password'" /> </div> <div class="form-item clearfix"> <router-link to="" class="login-link color-blue login-forget fr"><span class="iconfont icon-wenhao" replace></span>忘記密碼</router-link> </div> <button class="form-btn bg-blue" type="submit">登入</button> </form>