Search code examples
vue.jsvuejs2vuelidate

Display errors in v-for loop VueJs


I try to display error for each field from a v-for. But I get an error " Cannot read property '$error' of undefined", and I am not sure why.

<b-row  v-for="(v,index) in $v.years.$each.$iter" :key="index">
    <b-col>
        <b-form-group>
            <b-form-select
                v-model="v.year.$model"
                :class="{
                    'is-invalid':$v.year.$error, 'is-valid':!$v.year.$invalid}"
            ></b-form-select>
            <div class="invalid-feedback" v-if="!$v.year.required">This field is required!</div>
        </b-form-group>
    </b-col>
</b-row>

validations: {
    years:{
        $each:{
            year:{
                required
            },
        },
    }
},

UPDATE:

If I remove year from :class and v-if, it works, but if I have one error, It shows on each field, instead of just one.


Solution

  • This is why you shouldn't have such confusing naming scheme. It cannot find $error because $v property doesn't exist in your loop.

    You named the variable v not $v:

    v-for="(v,index) in $v.years.$each.$iter"