使用Element-UI的form表单验证文件是否上传

项目中有个需求,表单中的文件为必传项。

 其中使用了element-ui的form表单验证,话不多说,上代码。

复制代码
<template>
  <div>
    <el-form
      label-position="top"
      :model="reportForm"
      ref="checkerForm"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="上传报告" prop="checkFile">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :file-list="reportForm.reportFile"
          :on-change="uploadChange"
          :on-remove="uploadRemove"
          :limit="5"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rules: {
        checkFile: [
          { required: true, validator: this.fileMustUpload, trigger: "change" },
        ],
      },
      reportForm: {
        reportFile: [],
      },
    };
  },
  methods: {
    fileMustUpload(rule, value, callback) {
      if (this.reportForm.reportFile.length === 0) {
        callback("请上传附件");
      } else {
        callback();
      }
    },
    uploadChange(file, fileList) {
      this.$refs["checkerForm"].validateField(["checkFile"]);
    },
    uploadRemove(file, fileList) {
      this.$refs["checkerForm"].validateField(["checkFile"]);
    },
  },
};
</script>
复制代码

其中主要验证规则在红框部分。当然附件每次on-change和on-remove的时候都会重新校验一次。

 

posted on   hanguahannibk  阅读(1051)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示