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

如何使用Vuelidate验证空对象?选择场景下的空对象验证问题

How to Validate Empty Objects with Vuelidate for Selection Scenarios

I get it—you're trying to flag an empty object (like {id: null, name: null}) as invalid in Vuelidate, specifically for a selection scenario where only a populated object should pass validation. The default required validator doesn't cut it here because it only checks if the value itself exists (not whether its properties are empty).

Let's fix this with a custom validator tailored to your use case:

Vue.use(window.vuelidate.default)
const { required } = window.validators

// Custom validator: Checks if the object has at least one non-empty property
const requiredSelectedObject = value => {
  // Safeguard: If the value itself is null/undefined, mark as invalid
  if (!value) return false
  // Return true only if at least one property isn't null/undefined
  return Object.values(value).some(val => val !== null && val !== undefined)
}

new Vue({
  el: "#app",
  data: {
    companies: [
      { id: 1, name: 'facebook' },
      { id: 2, name: 'apple' }
    ],
    text: { id: null, name: null }
  },
  validations: {
    text: {
      // Replace default required with our custom validator
      required: requiredSelectedObject
    }
  }
})

Breakdown of the solution:

  • The requiredSelectedObject validator first checks if the value itself is null or undefined (a safeguard for edge cases).
  • It then uses Object.values(value).some(...) to scan all properties in the object. If even one property has a value that's not null or undefined, the validation passes. If all properties are empty, it fails—exactly what you need for a selection scenario where only a chosen item should be valid.

If your use case needs to account for empty strings too (e.g., if a property could be '' and you want that to count as invalid), tweak the check like this:

return Object.values(value).some(val => val !== null && val !== undefined && val !== '')

This custom validator is flexible and works no matter how many properties your object has—perfect for dynamic selection workflows.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:30:59