DEV Community

Raj
Raj

Posted on

How to use Vuelidate forEach helper to validate collections in Vue Js

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>
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)