VUE驗證器哪家強? VeeValidate absolutely!
VUE驗證器哪家強? VeeValidate absolutely!
vee-validate表單驗證用法
github地址:https://github.com/baianat/vee-validate
NPM地址:https://www.npmjs.com/package/vee-validate
DOC地址:https://baianat.github.io/vee-validate/guide/
線上演示地址:https://codesandbox.io/s/y3504yr0l1?initialpath=%2F%23%2Fform&module=%2Fsrc%2Fcomponents%2FForm.vue
vee-validate使用教程
本文適合有一定Vue2.0基礎的同學參考,根據專案的實際情況來使用,關於Vue的使用不做多餘解釋。本人也是一邊學習一邊使用,如果錯誤之處敬請批評指出
一、安裝
npm install [email protected] --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 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例項傳遞進來的。
提醒:養成好習慣,給每個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', '[email protected]'); // true
validator.validate('email', '[email protected]'); // false
//或者同時校驗多個:
validator.validateAll({
email: '[email protected]',
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} - 值必須符合正則pattern
required - 不解釋
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);