When the el-form form has asynchronous verification, how to perform overall verification on the form?

If element-ui is used in the project, when the form function needs to be implemented, element-ui's el-form form will definitely be used for programming.

prologue:

First, let’s take a look at the official documentation of el-form: 

method name illustrate parameter
validate A method for validating the entire form. The parameter is a callback function. This callback function will be called after the verification is completed , and two parameters will be passed in: whether the verification was successful and the fields that failed the verification. If no callback function is passed in, a promise will be returned Function(callback: Function(boolean, object))

The two sentences marked in red are very important.

Hidden dangers:

Now that we have the official method, we can use the validate method to verify the form as a whole before submitting the form. Then we may use the following writing method:

let hasError = false; //表单是否有报错的标志

//表单校验逻辑
this.$refs['ruleForm'].validate((valid) => {
    if (valid) {
        //表单有报错,将hasError置为true
        hasError = true;
    }
});

//如果表单有报错,return,阻止 表单提交
if(hasError){
    return
}

//下方是校验通过后,表单提交的逻辑
//xxxxxxx

↑↑↑↑When many students verify the logic of the form, they may write it like the above. First call the validate method of el-form, and use valid in the callback function to determine whether the form has an error. After calling the validate method Determine whether the form has an error to prevent form submission.

This way of writing has "security risks" :

  1. When there is no asynchronous verification in the rules field verification rules of el-form, the above code is executed synchronously. After calling the validate method, you can get hasError correctly. In this case, there is no problem in writing like this.
  2. However, if there is asynchronous verification (explanation at the bottom) in the rules field verification rules of el-form, then the callback function in validate is executed asynchronously. At this time, the logic of submitting the form will be followed regardless of whether there is an error in the form↓ ↓↓↓↓        
let hasError = false; //表单是否有报错的标志

//表单校验逻辑(存在异步校验)
this.$refs['ruleForm'].validate((valid) => {
    if (valid) {
         
        //异步校验,异步执行,会在下面的代码if(hasError)之后执行,才能拿到异步执行的结果(正确的hasError的值)

        //表单有报错,将hasError置为true
        hasError = true;
    }
});

//如果表单有报错,return,阻止 表单提交(这里是同步执行的代码,会先执行这句,然而hasError在这一步永远是false)
if(hasError){
    return
}

//下方是校验通过后,表单提交的逻辑
//xxxxxxx

solve:

Method 1: Put the form submission logic directly into the callback function

If you feel that the form submission logic is too much, write a separate function and call it in the callback function.


//表单校验逻辑(存在异步校验)
this.$refs['ruleForm'].validate((valid) => {
    
    if (!valid) {
         //表单校验有报错,return,代码不再往下执行
         return
    }
    
    //表单提交校验写到回调函数内
    //表单校验通过,进入表单提交逻辑
    //xxxxxxx

});

Method 2: Use async/await and try catch combination to perform form verification

Official description: If the validate method does not pass in a callback function, a promise will be returned . If there is no error in the form verification, resolve(valid) is executed inside validate, and if it fails, reject(valid) is executed (see the el-form source code for the specific internal implementation of this). In this way, a combination of async/await and try catch can be used for form verification .

async submitForm() {
    try {
      //调用表单的validate方法,执行表单校验
      await this.$refs['ruleForm'].validate()
    }catch(e) {
      //如果表单有报错,则进入catch,此时直接return不执行表单提交
      return
    }

    //表单校验通过,进入表单提交逻辑
    //xxxxxxx
}

Supplement: What is asynchronous verification?

In some scenarios, the form fields need to call an interface to pass the input value of an input box to the server for verification. After the server side completes the verification, it returns the verification result. This situation is an asynchronous verification.

The overall form verification validate function of el-form waits for all form fields (including asynchronous verification fields) to be verified before executing the callback function in validate. This will cause the "security risk" I mentioned earlier.

example:

 <el-form-item label="名称:" prop="name">
    <el-input
          v-model.trim="formDetail.name"
          placeholder="1-20个字符"   
     />
</el-form-item>

data() {
    //校验规则
    formRules = {
        //name字段需要进行异步校验
        name: [
             validator: (rule, val, cb) => {
                  //发送ajax到服务端进行校验
                  this.$http({
                      url: "/service/ajax-checkname",
                      method: "get",
                      data: {
                          name: val
                      }
                  }).then(res => {
                      let result = res.data;
                      if (!result.status) {
                         cb(result.message); //校验不通过,报错
                      } else {
                         cb(); //校验通过
                      }
                 });
            },
            trigger: "blur"
        ]
    }
}

Guess you like

Origin blog.csdn.net/weixin_46422035/article/details/125596836