如何使用Vuelidate验证空对象?选择场景下的空对象验证问题
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
requiredSelectedObjectvalidator first checks if the value itself isnullorundefined(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 notnullorundefined, 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

