vue中使用validate.js避坑

208 阅读1分钟

validate.js 使用避坑

form表单验证validate()后续执行条件:所有字段验证函数callback()回调必须执行完成

  • 模板
<template>
  <div class="container">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
          // 需要验证的表单组件
        <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
        // 提交表单
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template><script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
          
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    return {
      ruleForm: {
        pass: '',
      },
      rules: {
        pass: [{ validator: validatePass, trigger: 'blur' }],
      },
    };
  },
    methods: {
        submitForm(formName) {
         this.$refs[formName]
        .validate()
        .then(res => console.log('res', res))
        .catch(err => console.log('err', err));
        }
    }
};
</script>

callback 风格模式调用

this.$refs[formName].validate(valid => {
    if (valid) {
      alert('submit!');
    } else {
      console.log('error submit!!');
      return false;
    }
  });

注意点:

  1. 字段验证callback()函数未执行,validate回调也不执行. form表单全部通过验证<全部调用callback(无参)>, valid=true,否则valid=false

promise 风格格式调用

this.$refs[formName]
        .validate()
        .then(res => console.log('res', res))
        .catch(err => console.log('err', err));

注意点:

  1. form表单全部通过验证<全部调用callback(无参)>,进入then()方法<res参数true>, 否则进入catch()方法<err为错误信息对象>