async-validator
步骤
- 引入,实例化
import Schema from 'async-validator'
const rules = {
username: { required: true, message: '请输入用户名' },
password: { required: true, message: '请输入密码' }
}
const validator = new Schema(rules)
data() {
form: {
username: '',
password: ''
},
validatorControl: {}
}
- 验证单个和整体
验证单个使用
失去焦点事件
,整体要能异步回调
methods: {
validatorInit() {
for (const key in rules) {
this.$set(this.validatorControl, key, false)
}
},
validate(e) {
const control = this.validatorControl
if (e) {
const prop = e.target?.attributes?.prop?.value
if (!prop) return
control[prop] = false
validator.validate(this.form, (errors, fields) => {
if (errors && fields[prop]) control[prop] = fields[prop][0].message
})
} else {
for (const key in control) {
control[key] = false
}
return new Promise((resolve, reject) => {
validator.validate(this.form, (errors, fields) => {
if (errors)
errors.forEach(item => {
this.validatorControl[item.field] = item.message
})
else resolve(true)
resolve(false)
})
})
}
},
}
- 绑定html属性,绑定焦点事件
<div class="form" @focusout="validate">
<vs-input v-model="form.username" prop="username">
<template v-if="validatorControl.username" #message-danger>{{ validatorControl.username }}</template>
</vs-input>
<vs-input type="password" v-model="form.password" prop="password">
<template v-if="validatorControl.password" #message-danger>{{ validatorControl.password }}</template>
</vs-input>
</div>
- click方法
async login() {
if (!(await this.validate())) return
...
}
完成
注意
- async-validator没有单独验证某个字段功能,所以只能筛选
- async-validator不能关闭console.warning
if (process.env.NODE_ENV !== 'production' && typeof window !== 'undefined' && typeof document !== 'undefined') {
warning = function warning(type, errors) {
if (typeof console !== 'undefined' && console.warn) {
if (errors.every(function (e) {
return typeof e === 'string';
})) {
console.warn(type, errors);
}
}
};
}