0


vue2以及vue3基于el-table实现表格正则校验功能

常见需求:

在项目中,通常会在表格中添加多条数据,并需要对添加的数据进行校验功能,这时候就是很头疼的事了,下面酱酱仔给你们写个示例,你们无脑粘贴复制即可。

注意事项:

1、校验里面用到了正则校验功能,大家可以参考 酱酱仔的lgb-x文档lgb-xhttps://yjfk.hgjt.cn:9901后续酱酱仔将会持续迭代更新lgb-x库以及对应的lgb-x文档(lgb-x库不做重复轮子,只做业务场景常用组件以及api公共方法,致力于打造更便捷组件,提升开发效率)

2、示例是vue2.0写法,vue3.0也可以无脑使用,不过需要换成组合式api写法即可。

实现介绍:

1、首先默认给表格数据每行设置 isKeyValid: false ,目的是为了表格一开始打开时候,每行上下边距为0。

  tableData: [
          {
            date: "",
            name: "",
            address: "",
            isKeyValid: false,
          },
          {
            date: "",
            name: "",
            address: "",
            isKeyValid: false,
          },
        ],

2、其次在模版里面表格外层嵌套el-from表单,表格列插槽字段嵌套el-form-item,同时需要动态绑定class样式。

<template>
  <div class="app-container">
    <div class="table-form">
      {{ {tableData} }}
      <div style="margin-right: 0">
        <el-button type="primary" @click="add">新增</el-button>
      </div>
      <el-form :model="{tableData}" ref="ruleForm" label-width="0px">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column label="日期">
            <template slot-scope="scope">
              <div :class="scope.row.isKeyValid ? 'rulesFail' : 'rulePass'">
                <el-form-item
                  label=""
                  :prop="`tableData[${scope.$index}].date`"
                  :rules="{
        validator: validateDate,
        trigger: ['blur', 'change'],
        id: scope.$index,
      },"
                >
                  <el-date-picker
                    v-model="scope.row.date"
                    value-format="yyyy-MM-dd"
                    type="date"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="姓名">
            <template slot-scope="scope">
              <div :class="scope.row.isKeyValid ? 'rulesFail' : 'rulePass'">
                <el-form-item
                  label=""
                  :prop="`tableData[${scope.$index}].name`"
                  :rules="{
                validator: validateName,
                trigger: ['blur', 'change'],
                id: scope.$index,
              },"
                >
                  <el-input type="input" v-model="scope.row.name" />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="地址">
            <template slot-scope="scope">
              <div :class="scope.row.isKeyValid ? 'rulesFail' : 'rulePass'">
                <el-form-item
                  label=""
                  :prop="`tableData[${scope.$index}].address`"
                  :rules="{
                  validator: validateAddress,
                  trigger: ['blur', 'change'],
                  id: scope.$index,
                },"
                >
                  <el-input type="input" v-model="scope.row.address" />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </div>
  </div>
</template>

3、然后再在css里面定义对应的动态绑定的class类名样式,为了清空自带的表格外边距。

<style scoped lang="scss">
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}

.rulesFail {
  margin: 18px 0 !important;
}

.rulePass {
  margin: 0 !important;
}
</style>

4、最后再methods方法里面写校验逻辑

<script>
export default {
  name: "DemoPage",
  components: {},
  data() {
    return {
        tableData: [
          {
            date: "",
            name: "",
            address: "",
            isKeyValid: false,
          },
          {
            date: "",
            name: "",
            address: "",
            isKeyValid: false,
          },
        ],

    };
  },
  methods: {
    add() {
      this.tableData.push({
        date: "",
        name: "",
        address: "",
        isKeyValid: false,
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$message.success("校验通过");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //校验日期
    validateDate(rule, value, callback) {
      if (value === "" || value === null) {
        this.tableData[rule.id].isKeyValid = true;
        callback(new Error("请输入日期"));
      } else {
        callback();
        // if (this.tableFormData.tableData[rule.id].isKeyValid) {
        //   this.tableFormData.tableData[rule.id].isKeyValid = false;
        // }
      }
    },
    //校验姓名

    validateName(rule, value, callback) {
      const regExp = /^[\u4e00-\u9fa5a-zA-Z]+$/;
      if (!regExp.test(value)) {
        this.tableData[rule.id].isKeyValid = true;
        callback(new Error("请输入有效的姓名(仅限中英文,不包含特殊符号)"));
      } else {
        callback();
      }
    },

    //校验地址
    validateAddress(rule, value, callback) {
      if (value === "" || value === null) {
        this.tableData[rule.id].isKeyValid = true;
        callback(new Error("请输入地址"));
      } else {
        callback();
      }
    },
  },
};
</script>

整个demo代码如下:粘贴放到项目页面参考即可

<!--
 * @Author: lgb1224 [email protected]
 * @Date: 2024-06-19 11:38:11
 * @LastEditors: LAPTOP-9J0AUDN8
 * @LastEditTime: 2024-08-01 17:38:54
 * @FilePath: \vue-admin\src\views\environmentMonitor\governanceFacilities\sulfurNitrate\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <div class="table-form">
      {{ {tableData} }}
      <div style="margin-right: 0">
        <el-button type="primary" @click="add">新增</el-button>
      </div>
      <el-form :model="{tableData}" ref="ruleForm" label-width="0px">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column label="日期">
            <template slot-scope="scope">
              <div :class="scope.row.isKeyValid ? 'rulesFail' : 'rulePass'">
                <el-form-item
                  label=""
                  :prop="`tableData[${scope.$index}].date`"
                  :rules="{
        validator: validateDate,
        trigger: ['blur', 'change'],
        id: scope.$index,
      },"
                >
                  <el-date-picker
                    v-model="scope.row.date"
                    value-format="yyyy-MM-dd"
                    type="date"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="姓名">
            <template slot-scope="scope">
              <div :class="scope.row.isKeyValid ? 'rulesFail' : 'rulePass'">
                <el-form-item
                  label=""
                  :prop="`tableData[${scope.$index}].name`"
                  :rules="{
                validator: validateName,
                trigger: ['blur', 'change'],
                id: scope.$index,
              },"
                >
                  <el-input type="input" v-model="scope.row.name" />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="地址">
            <template slot-scope="scope">
              <div :class="scope.row.isKeyValid ? 'rulesFail' : 'rulePass'">
                <el-form-item
                  label=""
                  :prop="`tableData[${scope.$index}].address`"
                  :rules="{
                  validator: validateAddress,
                  trigger: ['blur', 'change'],
                  id: scope.$index,
                },"
                >
                  <el-input type="input" v-model="scope.row.address" />
                </el-form-item>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "DemoPage",
  components: {},
  data() {
    return {
        tableData: [
          {
            date: "",
            name: "",
            address: "",
            isKeyValid: false,
          },
          {
            date: "",
            name: "",
            address: "",
            isKeyValid: false,
          },
        ],

    };
  },
  methods: {
    add() {
      this.tableData.push({
        date: "",
        name: "",
        address: "",
        isKeyValid: false,
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$message.success("校验通过");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //校验日期
    validateDate(rule, value, callback) {
      if (value === "" || value === null) {
        this.tableData[rule.id].isKeyValid = true;
        callback(new Error("请输入日期"));
      } else {
        callback();
        // if (this.tableFormData.tableData[rule.id].isKeyValid) {
        //   this.tableFormData.tableData[rule.id].isKeyValid = false;
        // }
      }
    },
    //校验姓名

    validateName(rule, value, callback) {
      const regExp = /^[\u4e00-\u9fa5a-zA-Z]+$/;
      if (!regExp.test(value)) {
        this.tableData[rule.id].isKeyValid = true;
        callback(new Error("请输入有效的姓名(仅限中英文,不包含特殊符号)"));
      } else {
        callback();
      }
    },

    //校验地址
    validateAddress(rule, value, callback) {
      if (value === "" || value === null) {
        this.tableData[rule.id].isKeyValid = true;
        callback(new Error("请输入地址"));
      } else {
        callback();
      }
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}

.rulesFail {
  margin: 18px 0 !important;
}

.rulePass {
  margin: 0 !important;
}
</style>

效果如下所示:

标签: vue.js elementui 前端

本文转载自: https://blog.csdn.net/weixin_53339757/article/details/140853554
版权归原作者 爱池鱼的酱酱仔 所有, 如有侵权,请联系我们删除。

“vue2以及vue3基于el-table实现表格正则校验功能”的评论:

还没有评论