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

如何使用Vuelidate验证含动态键的对象?

解决方案:使用Vuelidate的helpers.objectOf验证器

你可以直接用Vuelidate内置的helpers.objectOf验证器来实现需求,它专门用于处理动态键对象的批量验证,无需将对象改为数组结构。

完整代码示例

import { reactive } from 'vue'
import { useVuelidate, helpers } from '@vuelidate/core'
import { required, minLength } from '@vuelidate/validators'

// 你的表单数据
const form = reactive({ 
  record: {
    en: { foo: 'bar' }, 
    de: { foo: 'baz' }
  } 
})

// 验证规则
const rules = {
  record: {
    // 可选:确保至少有一个语言项
    minLength: helpers.withMessage('至少需要添加一种语言', minLength(1)),
    // 给record下的每个属性值应用相同的验证规则
    objectOf: helpers.objectOf({
      foo: { required }
    })
  }
}

// 初始化Vuelidate实例
const v$ = useVuelidate(rules, form)

关键说明

  • helpers.objectOf会自动将传入的规则套用到record对象的所有属性值上,后续动态添加的语言键(比如fr、jp)会自动继承这套验证规则。
  • 验证状态的访问和常规对象一致:
    • 检查单个字段:v$.record.en.foo.$error
    • 检查整个record的验证状态:v$.record.$error
    • 检查所有字段的总状态:v$.$error

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 17:56:04