使用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 2024-04-01 18:05 hanguahannibk 阅读(926) 评论(0) 编辑 收藏 举报