Search code examples
vue.jsvuelidate

Strange behaviour of collection-validation in vuelidate


I have made the following minimal example, which can also be tested in this fiddle:

HTML:

<div id="app">
  <div v-for="(gameV, index) in $v.games.$each.$iter">
    <input type="text" :class="{error: gameV.$error, dirty: gameV.$dirty}" v-model="gameV.name.$model" />
    <input type="button" value="-" @click="games.splice(index, 1)" style="cursor: pointer;"/>
  </div>
  <input type="button" value="+" @click="games.push({name: ''})" style="cursor: pointer; margin-top: 5px;"/>

  <div v-if="$v.$invalid" style="color: red; margin-top: 1em;">Form invalid</div>
  <pre>{{ $v }}</pre>
</div>

JS:

Vue.use(vuelidate.default)

new Vue({
  el: "#app",
  data: {
    games: [{name: "Fallout"}, {name: "WoW"}, {name: ""}]
  },
  validations: {
    games: {
        $each: {
        name: {
            required: validators.required
        }
      }
    }
  }
})

Steps to reproduce the error:

  1. Type something in the second line.
  2. Remove second line.

Result: The former third line (now second) is marked as containing an error, even though it was not touched.

Note I've also filed an issue on the vuelidate github-repo, but as there are many unanswered issues, I have decided to also ask the question here.


Solution

  • https://jsfiddle.net/jacobgoh101/cqye5van/

    You can use $trackBy to solve this.

    enter image description here

    If you use $trackBy: 'id', the validation will be differentiated based on the id in each game. Each game object in the array would need to have a unique id for this to work.

    e.g. games: [{name: "Fallout", id: 1}, {name: "WoW", id: 2}, {name: "", id: 3}]