当前位置:   article > 正文

el-form 校验数组的每个元素_el-form 数组校验

el-form 数组校验

当表单的属性为数组时,该怎么校验数组元素的每一项呢?

效果图:
在这里插入图片描述
vue 代码

<template>
  <div style="width: 500px">
    <el-form
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      ref="ruleForm"
    >
      <el-form-item label="书籍推荐" prop="bookRecList">
        <div style="display: flex; margin-bottom: 10px">
          <el-button type="primary" @click="ruleForm.bookRecList.push('')">添加书籍</el-button>
        </div>
      </el-form-item>
       <div v-for="(item, index) in ruleForm.bookRecList" :key="index">
        <!-- rules也可以直接赋值规则, 如:
          :rules="[
            { required: true, message: '书籍名称不能为空', trigger: 'change' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'change'}
            ]"
         -->
         
          <el-form-item :prop="`bookRecList[${index}]`" :rules="rules.book">
            <el-input
              placeholder="请输入内容"
              v-model="ruleForm.bookRecList[index]"
            >
              <span slot="suffix"> {{ item.length }}/10 </span>
            </el-input>
          </el-form-item>
        </div>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    const validBookRecList = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error("至少推荐一个书籍"));
      } else {
        callback();
      }
    };
    const validBook = (rule, value, callback) => {
      console.log(rule);
      if (value === "" || value === null) {
        callback(new Error("请输入书籍名称"));
      } else {
        if (value.length > 10) {
          callback(new Error("书籍名称长度不超过10"));
        }
        callback();
      }
    };
    return {
      ruleForm: {
        bookRecList: [""],
      },
      rules: {
        bookRecList: { validator: validBookRecList, trigger: "change" },
        book: { validator: validBook, trigger: "change" },
      },
    };
  },
};
</script>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/112946
推荐阅读
相关标签