当前位置:首页 > IT技术 > Web编程 > 正文

Element-ui中 表单(Form)校验的几种形式 及 表单嵌套表格含上传(Upload)组件的
2021-10-21 23:07:41

1. Element-ui中 表单(Form)校验的几种形式

1.1 基础 / 自定义

在 el-form 上绑定 rules,rlues为校验规则,在 el-form-item 上绑定对应的prop;
自定义规则,validator:checkAge,自定义规则的函数。
详细的可查看 element 文档 http://element-cn.eleme.io/#/zh-CN/component/form

<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
    <el-form-item label="活动名称" prop="name">
      <el-input v-model="ruleForm.name"></el-input>
    </el-form-item>
    <el-form-item label="年龄" prop="age">
      <el-input v-model.number="ruleForm.age"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>  
</template>

<script>
var checkAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('年龄不能为空'));
  }
  if (!Number.isInteger(value)) {
    callback(new Error('请输入数字值'));
  } else {
    if (value < rule.max_age) {
      callback(new Error('必须年满18岁'));
    } else {
      callback();
    }
  }
};

export default {
  data() {
    return {
      ruleForm: {
        name: '',
        age:''
      },
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        age: [
          {max_age:18, validator: checkAge, trigger: 'blur' }// checkAge自定义规则函数
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!')
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

1.2 行间校验

<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px">
  <el-form-item
    label="年龄"
    prop="age"
    :rules="[
      { required: true, message: '年龄不能为空'},
      { type: 'number', message: '年龄必须为数字值'}
    ]">
    <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
  </el-form-item>
</el-form>  

1.4 行间自定义校验

<template>
  <el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px">
    <el-form-item
      label="年龄"
      prop="age"
      :rules="[
        {max_age:18, validator: checkAge, trigger: 'blur' }
      ]">
      <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return{}
  },
  methods: {
    checkAge(rule, value, callback){
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'));
      } else {
        if (value < rule.max_age) {
          callback(new Error('必须年满18岁'));
        } else {
          callback();
        }
      }
    },
  }
}
</script>

1.5 行间循环自定义校验

关键代码 :prop="domains.${index}.value",这是 Element-ui 规定的格式,渲染后的结果为:domains.1.value。

<template>
  <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px">
    <el-form-item
      v-for="(item, index) in dynamicValidateForm.domains"
      :key="item.index"
      :label="'域名' + index"
      :prop="`domains.${index}.value`"
      :rules="[
        { required: true, message: '域名不能为空', trigger: 'blur' },
        { reg:/^--------$/, validator: checkDomain, trigger: 'blur' }
      ]">
      <el-input v-model="item.value" placeholder="请输入内容"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      dynamicValidateForm: {
        domains: [
          { value: ''},
          { value: ''},
          { value: ''},
        ]
      }
    };
  },
  methods: {
    checkDomain(rule, value, callback){
      //自定义校验规则
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
        }
      });
    }
  }
}
</script>

2. 综合应用

案例中, Element-ui 表单里嵌套了表格,表格内每个单元格都能进行表单控件的输入、选择、上传文件等操作,同时能针对整个表单的规则进行校验。

在这里插入图片描述

<template>
  <div>
    <el-button type="primary" size="mini" @click="saveTableForm('tableForm')">保存</el-button>
    <el-form
      :model="tableForm"
      ref="tableForm">
      <el-table
        :data="tableForm.tableData"
        border
        stripe>
        <el-table-column label="省份" prop="province"></el-table-column>
        <el-table-column label="城市">
          <template slot-scope="scope">
            <el-form-item
              label=" "
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.city'"
              :rules="tableDataRules.city">
              <el-select size="mini" v-model="scope.row.city" placeholder="请选择" clearable>
                <el-option
                  v-for="item in scope.row.cityOPtions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作人">
          <template slot-scope="scope">
            <el-form-item
              label=" "
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.name'"
              :rules="tableDataRules.name">
              <el-input v-model="scope.row.name" placeholder="操作人" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="文件">
          <template slot-scope="scope">
            <el-form-item
              label=" "
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.file'"
              :rules="tableDataRules.file">
              <!-- 在组件的回调函数里加一个索引的参数 -->
              <el-upload
                multiple
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-progress="function(event,file,fileList){
                  return handleUploadProgress(event,file,fileList)}"
                :on-remove="function(file,fileList){
                  return handleUploadRemove(file,fileList,scope.$index)}"
                :on-success="function(res,file,fileList){
                  return handleUploadSuccess(res,file,fileList,scope.$index)}"
                :file-list="uploadFileList[scope.$index]">
                <el-button type="text">上传文件</el-button>
              </el-upload>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableForm: {
        tableData: [
          {
            province: "湖北",
            city: "",
            cityOPtions:[
              {label: '武汉市',value:'武汉市'},
              {label: '宜昌市',value:'宜昌市'}
            ],
            name: "",
            file:'',
          },{
            province: "重庆",
            city: "",
            cityOPtions:[
              {label: '渝北区',value:'渝北区'},
              {label: '九龙坡区',value:'九龙坡区'}
            ],
            name: "",
            file:'',
          },
        ],
      },
      tableDataRules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        city: [
          { required: true, message: "请选择城市", trigger: "change" },
        ],        
        file: [
          { required: true, message: "请上传文件", trigger: "change" },
        ],
      },
      uploadFileList:[[]], // 上传文件列表
    };

  },
  methods: {
    // 保存
    saveTableForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('校验通过',this.tableForm,this.uploadFileList)
        }
      });
    }, 
    // 预览图片
    handleUploadProgress(event,file,fileList) {},
    // 删除图片
    handleUploadRemove(file, fileList, index) {
      this.tableForm.tableData[index].file = '';
      this.uploadFileList[index] = fileList;
    },
    // 文件上传
    handleUploadSuccess(res, file, fileList, index) {
      this.tableForm.tableData[index].file = res.id;
      // 上传之后,把返回的fileList赋值给对应组件的fileList
      this.uploadFileList[index] = fileList;
    }
  },
};
</script>

本文摘自 :https://blog.51cto.com/u

开通会员,享受整站包年服务立即开通 >