validateAll doesn't work with inputs generated by v-for

Viewed 888

I've got a form in which the inputs are added dynamically with the v-for loop. Each field should be validated, and before user submit the form it should be checked wherever it's valid or not. The problem is that the this.$validator.validateAll() always return true, even if the inputs are invalid. What I'm doing wrong?

<div id="app">
  <v-app id="inspire">
    <v-flex md4 offset-md4>
  <form data-vv-scope="photoForm">
    <v-text-field v-for="index in 5" 
                  :key="index" 
                  :label="'photo' + index"
                  :error-messages="errors.collect('photoForm.photoName' + index)" 
                  v-validate="'max:10'"
                  :data-vv-name="'photoForm.photoName' + index"
                  color="purple" autocomplete="on"
                  counter="10"    >  
    </v-text-field>
  </form>
      <p>Is valid form? {{ validationResult }}</p>
      </v-flex>
  <v-btn @click="validate" color="purple" dark>
    validate
  </v-btn>
    </v-app>
</div>

Vue.use(VeeValidate);
new Vue({
  el: "#app",  
  data() {
    return {
      validationResult: ''
    }
  },
  methods: {
    validate() {
      this.$validator.validateAll('photoForm').then(result => {
        this.validationResult = result
      })
    }    
  }
});

And codepen where I reproduce the problem: https://codepen.io/anon/pen/jjrJdE

1 Answers

You need to store your form data somewhere so the validation has something to work on, I assume.

See https://codepen.io/cwg999/pen/MMjWNj?editors=1011

The main changes I made were to put your dynamically generated inputs into your data() and used that to reference them in the for-loop.

(note: you can also use v-model instead of :value/@input)

<v-text-field v-for="o,i in photoForm" 
              :key="i" 
              :label="o.label+ ' ' + (i+1)"
              :error-messages="errors.collect('photoForm.photoName' + i)" 
              v-validate="'max:10'"
              :name="'photoName' + i"
              :value=o.value
              @input="o.value = $event"
              color="purple" autocomplete="on"
              counter="10"    >  
</v-text-field>




data() {
    return {
      validationResult: '',
      photoForm:[
        {label:'Photo',value:''},
        {label:'Photo',value:''}
      ]
    }
  },
Related