##vue-form-check (基於vue的表單驗證)vue
// 安裝
npm i vue-form-check -S
複製代碼
// 引用(eg. 在工程的main.js下)
import vueFormCheck from 'vue-form-check'
Vue.use(vueFormCheck)
複製代碼
this.$checkForm(current, config)
@params
current 是當前校驗對象
config 是校驗規則對象
config.alias 別名
config.type 配置項數據類型
config.required 是否必填、非空驗證
經常使用不一樣類型初始化爲空條件
1、number 類型: Infinity, -Infinity
2、array 類型: []
3、string 類型: ''
4、object 類型: {}
5、function 類型: new Function() // null 和 undefined 賦值以後就不是相應的類型,會不經過,不可用 六、undefined 類型: undefined 七、null 類型: null // 特殊狀況,可經過將 boolean, regexp 轉換爲 string 類型進行驗證 八、boolean 類型: 初始化默認爲false,沒法觸發非空檢驗 九、regexp 類型: 初始化默認爲/(?:)/,沒法觸發非空檢驗 config.rule 正則校驗 config.depend 先決條件(省事能夠在callback裏直接判斷,推薦寫,true校驗本項;false不校驗本項) config.callback 靈活校驗(rule同時出現,只處理callback,參數是當前值,true校驗經過;false校驗不經過) @return object 對象 不經過的話 {alias: '電話', type: 'rule'} alias是配置的別名,type能夠是['type'|'required'|'rule']
校驗經過的話 {} 空對象
ps. 驗證表單能夠寫在mixin裏,這裏簡單處理直接寫在組件裏了
複製代碼
// 使用例子
new Vue({
data() {
return {
params: {
id: '1234',
person: {
name: 'jackie',
age: '27',
phone: '18266666666',
home: ['羅湖區田心村']
}
}
}
},
methods: {
submit() {
//...
console.log('submit success');
},
check() {
let obj = this.$checkForm(this.params, {
id: {
alias: 'id',
type: 'string'
},
// 必填校驗
'person.name': {
alias: '學校',
type: 'string',
required: true
},
// 正則校驗
'person.phone': {
alias: '電話',
type: 'string',
rule: /^1[345678][0-9]{9}$/
},
// 靈活校驗,如數值、日期區間驗證
'person.age': {
alias: '年齡',
callback(value) {
if (value < 30 && value > 18) {
return true;
}
return false;
}
},
// 先決校驗,若是電話等於如下,校驗地址信息
'person.home': {
alias: '方向',
type: 'array',
required: true,
depend() {
if (this.params.person.phone === '18210517463') {
return true;
}
return false;
}
}
});
const length = Object.keys(obj).length;
if (length === 0) {
return this.submit();
}
switch (obj.type) {
case 'type':
this.$alert(`${obj.alias}的類型定義錯誤`, '提示');
break;
case 'required':
this.$alert(`${obj.alias}是必填項`, '提示');
break;
case 'rule':
this.$alert(`${obj.alias}的輸入不符合規範`, '提示');
break;
default:
break;
}
}
}
});
複製代碼