Using the forEach helper from @vuelidate/validators , you can easily validate all properties inside a collection, without any extra components.
<template>
<div
v-for="(input, index) in state.collection"
:key="index"
:class="{
error: v$.collection.$each.$response.$errors[index].name.length,
}"
>
<input v-model="input.name" type="text" />
<div
v-for="error in v$.collection.$each.$response.$errors[index].name"
:key="error"
>
{{ error.$message }}
</div>
</div>
</template>
<script>
// setup in a component
import { helpers, required } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
import { reactive } from 'vue'
export default {
setup () {
const rules = {
collection: {
$each: helpers.forEach({
name: {
required
}
})
}
}
const state = reactive({
collection: [
{ name: '' }, { name: 'bar' }
]
})
const v = useVuelidate(rules, state)
return { v, state }
}
}
</script>
The $response for the validator follows the schema below, so you can use it as you wish:
const result = {
$data: [
{
propertyToValidate: {
validator: boolean,
}
},
],
$errors: [
{
propertyToValidate: [
{
$message: string, // the validator error
$model: '', // the model that was validated
$params: {}, // params, if validator has any
$pending: false, // always false, no async support.
$property: string, // the property to validate
$response: boolean, // response
$validator: string // validator name
},
]
},
{
name: []
}
],
$valid: boolean
}
Top comments (0)