Custom verification of a form field in el-form

To custom verify the value of a form field in el-form, you can use a custom verification function. You can do this by setting the prop attribute and rules attribute on el-form-item.

Here is an example:

<el-form ref="form" :model="formData" label-width="120px">
  <el-form-item label="名称" prop="name" :rules="[{ validator: validateName }]">
    <el-input v-model="formData.name"></el-input>
  </el-form-item>
  
  <el-form-item>
    <el-button type="primary" @click="submitForm">提交</el-button>
  </el-form-item>
</el-form>

In the above example, we added the prop attribute to el-form-item. The value of the prop attribute needs to correspond to the field name in the formData object. At the same time, the custom validation function validateName is specified in el-form-item through the rules attribute.

Next, define the validateName verification function in the Vue component:

export default {
    
    
  data() {
    
    
    return {
    
    
      formData: {
    
    
        name: ''
      }
    };
  },
  methods: {
    
    
    validateName(rule, value, callback) {
    
    
      // 进行自定义校验逻辑
      if (value === 'admin') {
    
    
        callback(new Error('名称不能为 admin'));
      } else {
    
    
        callback();
      }
    },
    submitForm() {
    
    
      this.$refs.form.validate((valid) => {
    
    
        if (valid) {
    
    
          // 校验通过,进行表单提交操作
          console.log('表单校验通过');
        } else {
    
    
          // 校验不通过,进行错误处理
          console.log('表单校验未通过');
        }
      });
    }
  }
};

In the above code, the entered name is custom verified through the validateName function. If the name is 'admin', call the callback function to pass error information, otherwise call the callback function without passing any parameters. At the same time, in this function, the data in data can also be used as a reference for judgment.

Finally, we call the validate method of el-form in the submitForm method to trigger form verification. In the callback function, perform corresponding processing based on the verification results.

Through the above steps, you can customize the value of a form field in el-form.

Guess you like

Origin blog.csdn.net/qq_47945175/article/details/132469902