vee-validate使用教程
*本文適合有一定Vue2.0基礎的同學參考,根據項目的實際情況來使用,關於Vue的使用不做多余解釋。本人也是一邊學習一邊使用,如果錯誤之處敬請批評指出*
一、安裝
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);
組件設置:
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還有更多應用,下面再講。
config其它參數,delay代表輸入多少ms之后進行校驗,messages代表自定義校驗信息,strict=true代表沒有設置規則的表單不進行校驗,errorBagName屬於高級應用,自定義errors,待研究
三、基礎使用
<div class="column is-12">
<label class="label" for="email">Email</label>
<p class="control">
<input v-validate data-rules="required|email" :class="{'input': true, 'is-danger': errors.has('email') }" name="email" type="text" placeholder="Email">
<span v-show="errors.has('email')" class="help is-danger">{{ errors.first('email') }}</span>
</p>
</div>
提醒:錯誤信息里面的名稱通常就是表單的name屬性,除非是通過Vue實例傳遞進來的。
提醒:養成好習慣,給每個field添加name屬性,如果沒有name屬性又沒有對值進行綁定的話,validator可能不會對其進行正確的校驗
關於errors:
上面的代碼我們看到有errors.has,errors.first,errors是組件內置的一個數據模型,用來存儲和處理錯誤信息,可以調用以下方法:
errors.first('field')- 獲取關於當前field的第一個錯誤信息collect('field')- 獲取關於當前field的所有錯誤信息(list)has('field')- 當前filed是否有錯誤(true/false)all()- 當前表單所有錯誤(list)any()- 當前表單是否有任何錯誤(true/false)add(String field, String msg)- 添加錯誤clear()- 清除錯誤count()- 錯誤數量remove(String field)- 清除指定filed的所有錯誤
關於Validator
Validator是以$validator被組件自動注入到Vue實例的。同時也可以獨立的進行調用,用來手動檢查表單是否合法,以傳入一個對象的方式,遍歷其中指定的field。
import { Validator } from 'vee-validate';
const validator = new Validator({
email: 'required|email',
name: 'required|alpha|min:3',
});
// or Validator.create({ ... });
你也可以在構造了validator之后設置對象參數
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
四、內置的校驗規則
after{target}- 比target要大的一個合法日期,格式(DD/MM/YYYY)alpha- 只包含英文字符alpha_dash- 可以包含英文、數字、下划線、破折號alpha_num- 可以包含英文和數字before:{target}- 和after相反between:{min},{max}- 在min和max之間的數字confirmed:{target}- 必須和target一樣date_between:{min,max}- 日期在min和max之間date_format:{format}- 合法的format格式化日期decimal:{decimals?}- 數字,而且是decimals進制digits:{length}- 長度為length的數字dimensions:{width},{height}- 符合寬高規定的圖片email- 不解釋ext:[extensions]- 后綴名image- 圖片in:[list]- 包含在數組list內的值ip- ipv4地址max:{length}- 最大長度為length的字符mimes:[list]- 文件類型min- max相反mot_in- in相反numeric- 只允許數字regex:{pattern}- 值必須符合正則patternrequired- 不解釋size:{kb}- 文件大小不超過url:{domain?}- (指定域名的)url
五、自定義校驗規則
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.
}
};
創建了規則之后,用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當成內置規則使用了:
<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.自定義內置規則的錯誤信息
import { Validator } from 'vee-validate';
const dictionary = {
en: {
messages: {
alpha: () => 'Some English Message'
}
},
cn: {
messages: {
alpha: () => '對alpha規則的錯誤定義中文描述'
}
}
};
Validator.updateDictionary(dictionary);
暫時介紹到這里,應該已經上手了,有空再繼續翻譯。
其它問題或者更高級應用,請參考官方文檔Vee-Validate
