插件窝 干货文章 Element UI表格表单校验:如何精准定位并标红错误项?

Element UI表格表单校验:如何精准定位并标红错误项?

校验 scope prop table 297    来源:    2025-03-26

Element UI 表格表单校验:精准定位并标红错误项

在 Element UI 中,表格内嵌表单校验是一个常见需求,特别是在可编辑表格场景中。下面我将详细介绍如何实现精准定位错误项并标红显示。

基本校验方法

1. 为表格项添加校验规则

首先需要在表格数据中为每个可编辑项定义校验规则:

data() {
  return {
    tableData: [
      {
        name: '',
        age: '',
        // 为每项添加校验规则
        rules: {
          name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          age: [
            { required: true, message: '请输入年龄', trigger: 'blur' },
            { type: 'number', message: '年龄必须为数字', trigger: 'blur' }
          ]
        }
      }
    ]
  }
}

2. 在表格列中使用表单校验

<el-table :data="tableData">
  <el-table-column prop="name" label="姓名">
    <template slot-scope="scope">
      <el-form-item :prop="'tableData.' + scope.$index + '.name'" 
                   :rules="scope.row.rules.name">
        <el-input v-model="scope.row.name"></el-input>
      </el-form-item>
    </template>
  </el-table-column>
  <!-- 其他列类似 -->
</el-table>

精准定位错误项

1. 使用 ref 获取表单实例

<el-form ref="dynamicForm"></el-form>

2. 校验特定行特定字段

validateField(rowIndex, prop) {
  this.$refs.dynamicForm.validateField(`tableData.${rowIndex}.${prop}`, (error) => {
    if (error) {
      // 找到对应单元格并高亮
      this.highlightErrorCell(rowIndex, prop);
    }
  });
}

3. 标红错误项实现

highlightErrorCell(rowIndex, prop) {
  // 清除之前的高亮
  document.querySelectorAll('.error-cell').forEach(el => {
    el.classList.remove('error-cell');
  });

  // 获取表格实例
  const table = this.$refs.table;
  // 获取行元素
  const row = table.$el.querySelectorAll('.el-table__row')[rowIndex];
  // 根据prop找到对应列索引
  const columnIndex = this.getColumnIndexByProp(prop);
  // 添加高亮类
  if (row && columnIndex !== -1) {
    const cell = row.querySelectorAll('.cell')[columnIndex];
    cell.classList.add('error-cell');
  }
}

// CSS样式
.error-cell {
  border: 1px solid #f56c6c;
  box-shadow: 0 0 3px #f56c6c;
}

完整示例

<template>
  <div>
    <el-form ref="dynamicForm">
      <el-table :data="tableData" ref="table">
        <el-table-column prop="name" label="姓名">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.name'" 
              :rules="scope.row.rules.name">
              <el-input 
                v-model="scope.row.name" 
                @blur="validateField(scope.$index, 'name')">
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄">
          <template slot-scope="scope">
            <el-form-item 
              :prop="'tableData.' + scope.$index + '.age'" 
              :rules="scope.row.rules.age">
              <el-input 
                v-model.number="scope.row.age" 
                @blur="validateField(scope.$index, 'age')">
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
      <el-button @click="validateAll">提交</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        {
          name: '',
          age: '',
          rules: {
            name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
            age: [
              { required: true, message: '请输入年龄', trigger: 'blur' },
              { type: 'number', message: '年龄必须为数字', trigger: 'blur' }
            ]
          }
        },
        // 更多行数据...
      ]
    }
  },
  methods: {
    validateField(rowIndex, prop) {
      this.$refs.dynamicForm.validateField(`tableData.${rowIndex}.${prop}`, (error) => {
        if (error) {
          this.highlightErrorCell(rowIndex, prop);
        } else {
          this.clearHighlight(rowIndex, prop);
        }
      });
    },
    highlightErrorCell(rowIndex, prop) {
      // 实现同上
    },
    clearHighlight(rowIndex, prop) {
      // 清除高亮
    },
    validateAll() {
      this.$refs.dynamicForm.validate(valid => {
        if (valid) {
          // 提交逻辑
        } else {
          // 自动定位第一个错误项
          this.autoScrollToFirstError();
        }
      });
    },
    autoScrollToFirstError() {
      // 实现自动滚动到第一个错误项
    }
  }
}
</script>

<style>
.error-cell {
  border: 1px solid #f56c6c;
  box-shadow: 0 0 3px #f56c6c;
}
</style>

高级技巧

  1. 批量校验优化:对于大型表格,可以使用 debounce 技术减少频繁校验

  2. 错误汇总显示:在表格顶部或底部显示所有错误信息汇总

  3. 自动滚动定位:校验失败时自动滚动到第一个错误项

  4. 自定义错误提示:使用 tooltip 或 popover 显示更详细的错误信息

通过以上方法,您可以实现 Element UI 表格内表单的精准校验和错误项定位,提升用户体验。