vee-validate使用教程
本文適合有一定Vue2.0基礎(chǔ)的同學(xué)參考,根據(jù)項目的實際情況來使用亲善,關(guān)于Vue的使用不做多余解釋设易。本人也是一邊學(xué)習(xí)一邊使用,如果錯誤之處敬請批評指出
一蛹头、安裝
npm install vee-validate@next --save
注意:@next,不然是Vue1.0版本
bower install vee-validate#2.0.0-beta.13 --save
二、引用
import Vue from 'vue';
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);
組件設(shè)置:
import VeeValidate, { Validator } from 'vee-validate';
import messages from 'assets/js/zh_CN';
Validator.updateDictionary({
zh_CN: {
messages
}
});
const config = {
errorBagName: 'errors', // change if property conflicts.
delay: 0,
locale: 'zh_CN',
messages: null,
strict: true
};
Vue.use(VeeValidate,config);
assets/js/zh_CN 代表你存放語言包的目錄戏溺,從node_modules/vee-validate/dist/locale目錄下面拷貝到你的項目
Validator還有更多應(yīng)用渣蜗,下面再講。
config其它參數(shù)旷祸,delay代表輸入多少ms之后進行校驗耕拷,messages代表自定義校驗信息,strict=true代表沒有設(shè)置規(guī)則的表單不進行校驗托享,errorBagName屬于高級應(yīng)用骚烧,自定義errors浸赫,待研究
三、基礎(chǔ)使用
<div class="column is-12">
<label class="label" for="email">Email</label>
<p class="control">
<input name="email"
type="text"
placeholder="Email"
v-validate
data-rules="required|email"
:class="{
'input': true,
'is-danger': errors.has('email')
}">
<span class="help is-danger" v-show="errors.has('email')" >{{ errors.first('email') }}</span>
</p>
</div>
提醒:錯誤信息里面的名稱通常就是表單的name屬性赃绊,除非是通過Vue實例傳遞進來的既峡。
提醒:養(yǎng)成好習(xí)慣,給每個field添加name屬性碧查,如果沒有name屬性又沒有對值進行綁定的話运敢,validator可能不會對其進行正確的校驗
關(guān)于errors:
上面的代碼我們看到有errors.has,errors.first,errors是組件內(nèi)置的一個數(shù)據(jù)模型,用來存儲和處理錯誤信息忠售,可以調(diào)用以下方法:
errors.first('field') - 獲取關(guān)于當(dāng)前field的第一個錯誤信息
collect('field') - 獲取關(guān)于當(dāng)前field的所有錯誤信息(list)
has('field') - 當(dāng)前filed是否有錯誤(true/false)
all() - 當(dāng)前表單所有錯誤(list)
any() - 當(dāng)前表單是否有任何錯誤(true/false)
add(String field, String msg) - 添加錯誤
clear() - 清除錯誤
count() - 錯誤數(shù)量
remove(String field) - 清除指定filed的所有錯誤
關(guān)于Validator
Validator是以$validator被組件自動注入到Vue實例的传惠。同時也可以獨立的進行調(diào)用,用來手動檢查表單是否合法,以傳入一個對象的方式稻扬,遍歷其中指定的field卦方。
import { Validator } from 'vee-validate';
const validator = new Validator({
email: 'required|email',
name: 'required|alpha|min:3',
});
// or Validator.create({ ... });
你也可以在構(gòu)造了validator之后設(shè)置對象參數(shù)
import { Validator } from 'vee-validate';
const validator = new Validator();
validator.attach('email', 'required|email'); // attach field.
validator.attach('name', 'required|alpha', 'Full Name'); // attach field with display name for error generation.
validator.detach('email'); // you can also detach fields.
最后你也可以直接傳值給field,測試是否可以通過校驗泰佳,像這樣:
validator.validate('email', 'foo@bar.com'); // true
validator.validate('email', 'foo@bar'); // false
//或者同時校驗多個:
validator.validateAll({
email: 'foo@bar.com',
name: 'John Snow'
});
//只要有一個校驗失敗了盼砍,就返回false
四、內(nèi)置的校驗規(guī)則
after{target} - 比target要大的一個合法日期乐纸,格式(DD/MM/YYYY)
alpha - 只包含英文字符
alpha_dash - 可以包含英文衬廷、數(shù)字、下劃線汽绢、破折號
alpha_num - 可以包含英文和數(shù)字
before:{target} - 和after相反
between:{min},{max} - 在min和max之間的數(shù)字
confirmed:{target} - 必須和target一樣
date_between:{min,max} - 日期在min和max之間
date_format:{format} - 合法的format格式化日期
decimal:{decimals?} - 數(shù)字吗跋,而且是decimals進制
digits:{length} - 長度為length的數(shù)字
dimensions:{width},{height} - 符合寬高規(guī)定的圖片
email - 不解釋
ext:[extensions] - 后綴名
image - 圖片
in:[list] - 包含在數(shù)組list內(nèi)的值
ip - ipv4地址
max:{length} - 最大長度為length的字符
mimes:[list] - 文件類型
min - max相反
mot_in - in相反
numeric - 只允許數(shù)字
regex:{pattern} - 值必須符合正則pattern
required - 不解釋
size:{kb} - 文件大小不超過
url:{domain?} - (指定域名的)url
五、自定義校驗規(guī)則
1.直接定義
const validator = (value, args) => {
// Return a Boolean or a Promise.
}
//最基本的形式宁昭,只返回布爾值或者Promise跌宛,帶默認的錯誤提示
2.對象形式
const validator = {
getMessage(field, args) { // 添加到默認的英文錯誤消息里面
// Returns a message.
},
validate(value, args) {
// Returns a Boolean or a Promise.
}
};
3.添加到指定語言的錯誤消息
const validator = {
messages: {
en: (field, args) => {
// 英文錯誤提示
},
cn: (field, args) => {
// 中文錯誤提示
}
},
validate(value, args) {
// Returns a Boolean or a Promise.
}
};
創(chuàng)建了規(guī)則之后,用extend方法添加到Validator里面
import { Validator } from 'vee-validate';
const isMobile = {
messages: {
en:(field, args) => field + '必須是11位手機號碼',
},
validate: (value, args) => {
return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
}
}
Validator.extend('mobile', isMobile);
//或者直接
Validator.extend('mobile', {
messages: {
en:field => field + '必須是11位手機號碼',
},
validate: value => {
return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
}
});
然后接可以直接把mobile當(dāng)成內(nèi)置規(guī)則使用了:
<input v-validate data-rules="required|mobile" :class="{'input': true, 'is-danger': errors.has('mobile') }" name="mobile" type="text" placeholder="Mobile">
<span v-show="errors.has('mobile')" class="help is-danger">{{ errors.first('mobile') }}</span>
4.自定義內(nèi)置規(guī)則的錯誤信息
import { Validator } from 'vee-validate';
const dictionary = {
en: {
messages: {
alpha: () => 'Some English Message'
}
},
cn: {
messages: {
alpha: () => '對alpha規(guī)則的錯誤定義中文描述'
}
}
};
Validator.updateDictionary(dictionary);