element表單后端校驗顯示錯誤
- 目的是輸入表單結(jié)合防抖指令和向后端校驗后錯誤文本顯示在錯誤區(qū)域而不是彈框形式
html
<el-form-item label="登錄手機號:" prop="phone" ref="phoneFormItem">
<el-input
v-model.number.trim="form.phone"
size="small"
v-debounce-input="checkPhone"
debounce-second="0.5"
placeholder="請輸入登錄手機號"
></el-input>
</el-form-item>
js
function check(rule, value, callback, error) {
console.log('newCheckPhone error', error)
error ? callback(new Error(error)) : callback()
}
function newValidate(fn) {
// 重新被new生成获高,所以this指向閉包函數(shù)本身
return function () {
console.log('newCheckPhone arguments', arguments, this)
fn(arguments[0], arguments[1], arguments[2], this.validator.error)
}
}
const phoneValidate = newValidate(check)
data(){
return {
rules: {
phone: [
{
required: true,
message: '登錄手機號不能為空',
trigger: ['blur', 'change']
},
{
pattern: /^1[345789]\d{9}$/,
message: '登錄手機號格式錯誤',
trigger: ['blur', 'change']
},
{
validator: phoneValidate,
trigger: 'blur'
}
]
}
}
}
methods: {
async checkPhone() {
let phoneError = ''
let _this = this
this.$refs.form.validateField('phone', function (validate) {
console.log('checkPhone validate', validate)
if (!['登錄手機號不能為空', '登錄手機號格式錯誤'].includes(validate)) {
_this.$refs.phoneFormItem.clearValidate()
phoneError = ''
} else {
phoneError = validate
}
})
console.log('checkPhone phoneError', phoneError)
if (phoneError) {
return
}
//校驗登錄手機號
let params = {
jdbPhone: this.form.phone
}
request(params).then(res => {
if (res.code === 200) {
phoneValidate.error = ''
} else {
phoneValidate.error = res.msg
}
//手動校驗 顯示錯誤文本
this.$refs.form.validateField('phone')
})
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者