day09-15 element表单后端校验显示错误

element表单后端校验显示错误

  • 目的是输入表单结合防抖指令和向后端校验后错误文本显示在错误区域而不是弹框形式
html

   
 
js
function check(rule, value, callback, error) {
  console.log('newCheckPhone error', error)
  error ? callback(new Error(error)) : callback()
}
function newValidate(fn) {
  // 重新被new生成,所以this指向闭包函数本身
  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')
      })
    }
}

你可能感兴趣的:(day09-15 element表单后端校验显示错误)