vue中vee-validate表單驗證元件(vux中驗證藉助方式)
阿新 • • 發佈:2018-12-25
vee-validate
安裝
npm install vee-validate --save
引用
import Vue from 'vue';
import VeeValidate from 'vee-validate';
VeeValidate.Validator.localize('zh_CN');//改變成zh_CN中文的語言環境,如果不改預設提示是英文
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);
基本演示
<input v-validate="'required|email'" name="email" type="text">
<!-- 錯誤展示 -->
<span>{{ errors.first('email') }}</span>
- v-validate 表單驗證指令
- name 確保表單的正確驗證,展示表單對應的驗證規則
- v-validate 傳遞規則(rules),使用管道符分割
- required 該領域是必需的
- email 表明該欄位必須為電子郵件
- errors.first 展示錯誤訊息
- errors.first(‘fieldName’) 顯示單個錯誤訊息
- errors.collect(‘fieldName’) 顯示多條錯誤訊息
- errors.all() 顯示所有錯誤訊息
- errors.collect() 按欄位名稱分組
預設驗證規則
- 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
參考連結:驗證規則
自定義規則
建立規則
<!-- 功能表 -->
const validator = (value, args) => {
// Return a Boolean or a Promise that resolves to a boolean.
};//最基本的形式,只返回布林值或者Promise,帶預設的錯誤提示
<!-- 物件表 -->
const validator = {
getMessage(field, args) {// 新增到預設的英文錯誤訊息裡面
// will be added to default locale messages.
// Returns a message.
},
validate(value, args) {
// Returns a Boolean or a Promise that resolves to a boolean.
}
};
使用自定義規則
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)
}
})
<!-- 使用 -->
<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>
//如果需求裡不需要多一個提示的標籤,只需要在錯誤驗證時顯示警示顏色,那可以通過在input標籤上寫 :class="{error:error.has('idCard')}" 來實現。