vue动态添加表单validateField验证功能实现

Vue
386
0
0
2023-09-16
标签   Vue实践

vue动态添加表单validateField验证,代码如下所示:

<template>
    <el-form ref="form" :model="form" :rules="rules" label-width="px">
      <div v-for="(input, index) in inputs" :key="index">
        <el-form-item :label="'Name ' + (index +)" :prop="'name' + index">
          <el-input v-model="input.name" @blur="validateName(index)"></el-input>
        </el-form-item>
        <el-form-item :label="'Age ' + (index +)" :prop="'age' + index">
          <el-input v-model.number="input.age" @blur="validateAge(index)"></el-input>
        </el-form-item>
      </div>
      <el-button type="primary" @click="addInput">Add input</el-button>
      <el-button type="primary" @click="submitForm">Submit</el-button>
    </el-form>
  </template>

  <script>
  export default {
    data() {
      return {
        form: {},
        inputs: [{name: '',age: ''}],
        rules: {
            name: { required: true, pattern: /^[A-Za-z]+$/, message: 'Name can only contain letters', trigger: 'blur' },
            age: { required: true, pattern: /^\d+$/, message: 'Age can only contain numbers', trigger: 'blur' },
        }
      }
    },
    methods: {
      addInput() {
        const index = this.inputs.length
        this.inputs.push({ name: '', age: '' })
        this.$set(this.form, `name${index}`, '')
        this.$set(this.form, `age${index}`, '')
        this.$set(this.rules, `name${index}`, { required: true, pattern: /^[A-Za-z]+$/, message: 'Name can only contain letters', trigger: 'blur' })
        this.$set(this.rules, `age${index}`, { required: true, pattern: /^\d+$/, message: 'Age can only contain numbers', trigger: 'blur' })
      },
      validateName(index) {
        this.$refs.form.validateField(`name${index}`)
      },
      validateAge(index) {
        this.$refs.form.validateField(`age${index}`)
      },
      submitForm() {
        this.$refs.form.validate(valid => {
          if (valid) {
            // submit form
          } else {
            console.log('validation failed')
          }
        })
      }
    }
  }
  </script>

可以使用 Element UI 的表单组件结合 Vue 的动态组件来实现动态添加多组输入框,并对每个输入框进行校验。Element UI 提供了很多内置的校验规则和提示信息,可以方便地应用到表单中。

首先,我们需要在 Vue 实例中声明一个 inputs 数组来存储每个输入组的数据。在添加输入组时,我们只需要向 inputs 数组中添加一个新的对象即可。

在模板中,我们使用 Element UI 的表单组件来渲染输入框,并使用 v-for 指令循环渲染多组输入框。在每个输入框中,我们使用 v-model 指令将输入值绑定到 inputs 数组中的数据属性上。对于 name 和 age 输入框,我们使用 pattern 规则来进行校验,并在 rules 对象中提供了相应的错误提示信息。在 checkNameInput 和 checkAgeInput 方法中,我们调用 $refs.form.validateField 方法来手动触发校验,并将当前输入对象作为参数传递进去。

最后,我们需要在 Vue 实例中声明一个 form 对象来维护表单数据,并将 rules 对象传递给 el-form 组件的 rules 属性。这样,每次输入框的值发生变化时,就会自动触发 Element UI 的校验机制,并显示相应的错误提示信息。

补充:vue动态表单添加表单验证

    <el-form ref="conditionListForm" :rules="ConditionListRules" :model="scope.row.conditionListForm">
      <el-table
        ref="conditionListDia"
        :data="scope.row.conditionListForm.conditionListDia"
        border
        :header-cell-style="background"
        style="width:%"
        size="mini"
      >
        <el-table-column label="限制条件名称" align="center">
          <el-table-column
            label="条件组合"
            align="center"
            size="mini"
            min-width=""
          >
            <template slot-scope="scopeChild">
              <el-form-item :prop=" 'conditionListDia[' + scopeChild.$index + '].conditionRelation' " :rules="ConditionListRules.conditionRelation">
                <el-select
                  v-model="scopeChild.row.conditionRelation"
                  :disabled="scope.row.conditionListForm.conditionListDia.length > || scope.row.id > 0"
                  size="mini"
                  placeholder="请选择"
                  clearable
                  style="float:left;width:%"
                  @change="showconditionRelation(scopeChild.row.conditionRelation)"
                >
                  <el-option
                    v-for="item in compositionConditionList"
                    :key="item.key"
                    :disabled="item.baseDataStatus===''"
                    :label="item.label"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="条件分组"
            size="mini"
            align="center"
            min-width=""
          >
            <template slot-scope="scopeChild">
              <el-form-item :prop=" 'conditionListDia[' + scopeChild.$index + '].medalConditionClassname' " :rules="ConditionListRules.medalConditionClassname">
                <el-select
                  v-model="scopeChild.row.medalConditionClassname"
                  :disabled="scope.row.id >"
                  size="mini"
                  placeholder="请选择"
                  clearable
                  style="float:left;width:%"
                  @change="defDataClick(scopeChild)"
                >
                  <el-option
                    v-for="item in fatherNameList"
                    :key="item.id"
                    :label="item.medalConditionClassname"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="条件"
            size="mini"
            align="center"
            min-width=""
          >
            <template slot-scope="scopeChild">
              <el-form-item :prop=" 'conditionListDia[' + scopeChild.$index + '].conditionId' " :rules="ConditionListRules.conditionId">
                <el-select
                  v-model="scopeChild.row.conditionId"
                  size="mini"
                  :disabled="scope.row.id >"
                  placeholder="请选择"
                  clearable
                  style="float:left;width:%"
                  @change="getRelationship(scopeChild.row.conditionId,scopeChild.row.medalConditionClassnameList,scopeChild.row)"
                >
                  <el-option
                    v-for="item in scopeChild.row.medalConditionClassnameList"
                    :key="item.defId"
                    :label="item.medalConditionName"
                    :value="item.defId"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column
          label="运算关系"
          align="center"
          size="mini"
          min-width=""
        >
          <template slot-scope="scopeChild">
            <el-form-item :prop=" 'conditionListDia[' + scopeChild.$index + '].conditionOperation' " :rules="ConditionListRules.conditionOperation">
              <el-select
                v-model="scopeChild.row.conditionOperation"
                size="mini"
                placeholder="请选择"
                :disabled="scope.row.id >"
                clearable
                style="float:left;width:%"
                @change="conditionOperationEmpty(scopeChild.row)"
              >
                <el-option
                  v-for="item in scopeChild.row.conditionOperationValueList"
                  :key="item.key"
                  :disabled="item.baseDataStatus===''"
                  :label="item.value"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="值"
          align="center"
          size="mini"
          min-width=""
        >
          <template slot-scope="scopeChild">
            <el-form-item v-if="scopeChild.row.medalConditionControlType === ''" :prop=" 'conditionListDia[' + scopeChild.$index + '].conditionTrueValueList' " :rules="ConditionListRules.conditionTrueValueList">
              <el-select
                v-model="scopeChild.row.conditionTrueValueList"
                multiple
                style="float:left;width:%"
                size="mini"
                clearable
                placeholder="请选择"
                @change="conditionValueEmpty(scopeChild)"
              >
                <el-option
                  v-for="item in scopeChild.row.conditionValueList"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="scopeChild.row.medalConditionControlType == ''" :prop=" 'conditionListDia[' + scopeChild.$index + '].conditionValue' " :rules="ConditionListRules.conditionValue">
              <el-input
                v-model="scopeChild.row.conditionValue"
                clearable
                placeholder="请输入"
                align="center"
                style="float:left;"
                size="mini"
                maxlength=""
                show-word-limit
                @blur="conditionValueEmpty(scopeChild)"
              />
            </el-form-item>
            <el-form-item v-if="scopeChild.row.medalConditionControlType == ''" :prop=" 'conditionListDia[' + scopeChild.$index + '].conditionTrueValueList' " :rules="ConditionListRules.conditionTrueValueList">
              <el-date-picker
                v-model="scopeChild.row.conditionTrueValueList"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                size="mini"
                end-placeholder="结束日期"
                style="float:left;width:%"
              />
            </el-form-item>
            <el-form-item v-if="scopeChild.row.medalConditionControlType === ''" :prop=" 'conditionListDia[' + scopeChild.$index + '].conditionValue' " :rules="ConditionListRules.conditionValue">
              <el-select
                v-model="scopeChild.row.conditionValue"
                style="float:left;width:%"
                size="mini"
                clearable
                placeholder="请选择"
                @change="conditionValueEmpty(scopeChild)"
              >
                <el-option
                  v-for="item in scopeChild.row.conditionValueList"
                  :key="item.value"
                  :label="item.key"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="scopeChild.row.medalConditionControlType === ''" :prop=" 'conditionListDia[' + scopeChild.$index + '].conditionTrueValueList' " :rules="ConditionListRules.conditionTrueValueList">
              <el-time-picker
                v-model="scopeChild.row.conditionTrueValueList"
                style="float:left;width:%"
                size="mini"
                is-range
                clearable
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
                format="HH:mm"
                @change="conditionValueEmpty(scopeChild)"
              />
            </el-form-item>
            <el-form-item v-if="scopeChild.row.medalConditionControlType == ''" :prop=" 'conditionListDia[' + scopeChild.$index + '].conditionValue' " :rules="ConditionListRules.conditionValue">
              <el-input-number v-model="scopeChild.row.conditionValue" size="mini" :min="" label="" @change="conditionValueEmpty(scope)" />
            </el-form-item>
            </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          min-width=""
        >
          <template slot-scope="scopeChild">
            <el-button type="text" :disabled="scope.row.id >" @click="delCondition(scope.$index,scope.row.conditionListForm.conditionListDia,scopeChild.row,scopeChild.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
 ConditionListRules: {
    conditionRelation: [{ required: true, message: '条件组合不能为空', trigger: 'change' }
    ],
    medalConditionClassname: [{ required: true, message: '条件分组不能为空', trigger: 'change' }
    ],
    conditionId: [{ required: true, message: '条件不能为空', trigger: 'change' }
    ],
    conditionOperation: [{ required: true, message: '运算关系不能为空', trigger: 'change' }
    ],
    conditionValue: [{ required: true, message: '值不能为空', trigger: 'change' }
    ],
    conditionTrueValueList: [{ required: true, message: '值不能为空', trigger: 'change' }
    ]
  },

主要就是prop的问题,prop要对应到数据。