1.安裝
cnpm install vee-validate --save
2.在assets文件夾下創(chuàng)建一個validate.js文件
'use strict';
import Vue from 'vue'
import VeeValidate, {Validator} from 'vee-validate'
import zh from 'vee-validate/dist/locale/zh_CN';//引入中文文件
// 配置中文
Validator.addLocale(zh);
const config = {
locale: 'zh_CN'
};
Vue.use(VeeValidate,config);
// 自定義validate
const dictionary = {
zh_CN: {
messages: {
email: () => '請輸入正確的郵箱格式',
required: ( field )=> "請輸入" + field
},
attributes:{
email:'郵箱',
password:'密碼',
name: '賬號',
phone: '手機'
}
}
};
Validator.updateDictionary(dictionary);
//擴展自定義的驗證询一,比如這邊自定義了電話的表單驗證隐孽。
Validator.extend('phone', {
messages: {
zh_CN:field => field + '必須是11位手機號碼',
},
validate: value => {
return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
}
});
3.在main.js中引入這個js文件
import "./assets/validata.js"
4.使用
在 HelloWord.vue文件中寫入一下測試代碼
<p>
<input v-validate="'required|email'" name="email" type="text" placeholder="Email">
<span v-show="errors.has('email')" >{{ errors.first("email") }}</span>
</p>
<p>
<input v-validate="'required|phone'" name="phone" type="text" placeholder="phone">
<span v-show="errors.has('phone')" >{{ errors.first("phone") }}</span>
</p>
5.運行
npm run dev