BootstrapVue Form Array/Collection Input with Vuelidate

April 9, 2020

Vuelidate v0.75 collections validation seems to work fine if the array or collection is objects. If the collection/array is native types (e.g. String), the changes/reactivity is not detected (not trigerring valiation rules, but the underlying value did indeed changed).

<template>
  <div>
    <b-form ref="form" @submit.prevent="submit">
      <b-form-group
        label="Name"
        label-for="input-name"
        invalid-feedback="Name is required"
      >
        <b-form-input
          :state="validateState($v.item.name)"
          id="input-name"
          v-model="$v.item.name.$model"
        ></b-form-input>
      </b-form-group>

      <!-- <div v-for="(v, index) in $v.friends.$each.$iter"> -->
      <b-row v-for="item, index in friends" :key="index">
        <b-col md="6">
          <b-form-input
            :state="validateState($v.friends.$each[index].name)"
            v-model="$v.friends.$each[index].name.$model">
          </b-form-input>
        </b-col>
        <b-col md="6">
          <b-form-input
            :state="validateState($v.friends.$each[index].age)"
            v-model="$v.friends.$each[index].age.$model">
          </b-form-input>
        </b-col>
      </b-row>

      <b-button type="submit" variant="primary">Submit</b-button>
    </b-form>
  </div>
</template>

<script>
import { validationMixin } from "vuelidate"
import { required, minLength } from "vuelidate/lib/validators"

export default {
  mixins: [validationMixin],
  // props: ['item'],
  data() {
    item: {
      name: 'Desmond',
      friends: [
        { name: 'Elon', age: 48 },
        { name: 'Jack', age: 43 },
        { name: 'Mei Ru', age: 40 }
      ]
    },
  },
  validations: {
    item: {
      name: {
        required
      },
      friends: {
        $each: {
            name: { required },
            age: { required }
        }
      },
    }
  },
  methods: {
    validateState(item) {
      const { $dirty, $error } = item
      return $dirty ? !$error : null
    },
    submit() {
      this.$v.item.$touch()
      if (this.$v.item.$anyError)
        return false

      console.log(this.item)
      alert("Form submitted!")
    }
  }
}
</script>
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.