likes
comments
collection
share

不一样的el-form校验

作者站长头像
站长
· 阅读数 13

起因

产品 :需要在点击保存时,校验每一列中 单选框选中的情况下校验 某某 文本框内容 单选框没有选中 则让文本框为空且置灰 我(内心):这咋搞啊,我只弄过校验没有 for循环在其中的,怎么获取每一列中的元素啊,脑袋混乱,应该要弄一段时间了 然后告诉产品:我先研究下

如何做

Element-plus 文档

查看Element-plus文档,el-form-item其中有一个API prop:model的键名,它可以是一个路径数组,也可以是string。在定义validate,resetFields方法时,该属性必填,prop属性是设置需要校验的字段名。 还有一个 API为rules,在项目中以前就是其他el-form-item用这个做的验证,然后查看文档,定义一个验证的函数,其第一个参数是rule,打印出来其中有一个field就是prop中传的值,所以我们可以从filed中获取该列中的index,如果该列中还存在v-for的循环,则再加上一个itemIndex,这样就可以拿到这一列中所有的值,也就解决了我们的问题。

demo

demo代码如下

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
     <template v-for="(item,index) in props">
      <el-form-item :prop ="'props.'+index">
      <el-checked v-model="item.checked">是否勾选</el-checked>
       <el-form-item label="pass" :rules="rules.checkPass" :prop="'props.'+index+'.pass'">
      <el-input   v-model="item.pass" type="password" autocomplete="off" />
    		</el-form-item>
      </el-form-item>
      <template>
   
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: any, callback: any) => {
  console.log(rule)// props.0(index).pass
	// 获取 index
  const index = rule.split('.')[1]
  // 获取该列的内容
  const item = ruleForm.props[index]
  // 如何校验看你自己了
  if (value === '') {
    callback(new Error('Please input the password again'))
  } else if (value !== ruleForm.pass) {
    callback(new Error("Two inputs don't match!"))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  props:[
    {pass: '',
     checked:true
    })}
  ]
  

const rules = reactive<FormRules>({
  checkPass: [{ validator: validatePass, trigger: 'blur' }],

})
</script>

这是我第一次在el-form中校验存在v-for的el-form-item,希望对有此需求的jym有所帮助,如果有啥不清楚的,评论区留言🤪