其他分享
首页 > 其他分享> > Element-UI 动态设置form验证规则

Element-UI 动态设置form验证规则

作者:互联网

问题:选择switch 改变 ruleForm.delivery 的值,动态实现校验生效

vue代码:

<template>
  <div id="app">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px">
      <el-form-item label="切换" prop="delivery">
        <el-switch v-model="ruleForm.delivery"></el-switch>
      </el-form-item>
      <el-form-item
        label="text"
        prop="desc"
        :required="ruleForm.delivery ? true : false">
        <el-input type="textarea" v-model="ruleForm.desc"></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() {
    let test = (rule, value, callback) => {
      if (!value && this.ruleForm.delivery) {
        callback(new Error("不能为空"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        delivery: false,
        desc: "",
      },
      rules: {
        desc: [{ trigger: "blur", validator: test }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

let test = (rule, value, callback) 验证规则函数要在定义 rules 之前

标签:ruleForm,false,form,value,Element,delivery,callback,UI,test
来源: https://www.cnblogs.com/2393920029-qq/p/15933040.html