#1072·vuelidate

forEach helper makes new entries to the collection dirty

Author: samul-1Created Jun 21, 2022Updated Feb 22, 2025
Labelsbug2.0

Using the sample code given in the docs for forEach:

bash
<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>

If I call $touch on collection, and then a new element is added to the collection, it'll be dirty as soon as it's added. I would expect that the existing elements would be dirty, and the new ones wouldn't. That way, errors wouldn't be displayed immediately and would instead require the user to interact with the element, as it's intended.

For example, this sample from an older version of vuelidate does just that: https://vuelidate.js.org/#sub-collections-validation

How do I get this behavior in the current version?