##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;
}
}
}
});
复制代码