You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Vuelidate实现Vue动态集合验证的需求与代码示例

如何在Vuelidate中实现依赖同对象属性的条件必填验证

针对你提出的数组对象验证需求——每个item的value字段必填,且仅当value等于otherKey时other字段才必填——我们可以利用Vuelidate内置的requiredIf验证器来轻松实现,无需自定义复杂的验证函数。

实现步骤:

  1. 从Vuelidate的validators中引入requiredIf(和已有的required一起)
  2. 在validations配置的other字段规则中,使用requiredIf传入一个判断函数,该函数会接收当前的item作为参数,返回item.value === item.otherKey的布尔值

完整代码示例

模板部分(无需修改)

<div id="app">
  <div v-for="(item, i) in items" :key="i">
    <input type="text" v-model="item.value" @input="$v.items.$each[i].$touch" :class="{error: $v.items.$each[i].value.$error}">
    <input type="text" v-model="item.other" @input="$v.items.$each[i].$touch" :class="{error: $v.items.$each[i].other.$error}">
  </div>
  <pre>{{ $v }}</pre>
</div>

JavaScript部分(修改验证规则)

Vue.use(window.vuelidate.default)
const { required, requiredIf } = window.validators // 引入requiredIf
new Vue({
  el: "#app",
  data: {
    items: [
      { value: 'A', other: 'B', otherKey: 'C' },
      { value: 'D', other: 'E' , otherKey: 'F' },
      { value: 'G', other: '' , otherKey: 'G' } // 这里value等于otherKey,other为空会触发错误
    ]
  },
  validations: {
    items: {
      $each: {
        value: { required },
        other: {
          // 当当前item的value等于otherKey时,other字段必填
          required: requiredIf(item => item.value === item.otherKey)
        }
      }
    }
  }
})

关键说明

  • requiredIf是Vuelidate专门用于条件必填的验证器,它接收一个返回布尔值的函数:
    • 当函数返回true时,对应的字段会被标记为必填项
    • 函数的参数就是当前遍历到的item对象,我们可以直接访问它的value和otherKey属性做判断
  • 模板中的$touch方法用于触发验证,确保用户输入时实时更新验证状态

这样修改后,就能完全满足你的验证需求:所有item的value字段必须填写;只有当某个item的value和otherKey值相等时,它的other字段才需要填写,否则可以为空。

内容的提问来源于stack exchange,提问作者AldoZumaran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:25:04