VeeValidate Scroll to first error

Example on how to implement scrolling to the first error.

by dauruk0512

HTML

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vee-validate.js"></script>
<div id="app">
  <h3>Scroll to end to click the button</h3>
  <div class="form-group">
    <input type="text" ref="emailInput" name="email" placeholder="email" v-validate="'required|email'">
    {{ errors.first('email') }}
  </div>
  
  <div class="form-group">
    <input type="text" ref="nameInput" name="name" placeholder="Name" v-validate="'required'">
    {{ errors.first('name') }}
  </div>
  
  
  <button @click="validate(false)">Validate Basic</button>
  <button @click="validate(true)">Validate Advanced</button>
</div>

CSS

#app button {
  margin-top: 700px;
  padding: 20px;
}

.form-group {
   padding: 20px;
   margin-bottom: 50px;
}

JavaScript

Vue.use(VeeValidate);

new Vue({
	el: '#app',
  methods: {
  	handleValidationErrorAdvanced () {
    	const firstField = Object.keys(this.errors.collect())[0];
      
      // this assumes you have a conviention of ref and field name here I just add the
      // Input suffix to the field name as you can see in the template.
      this.$refs[`${firstField}Input`].scrollIntoView();
    },
  	handleValidationErrorBasic () {
    	// if there is an email error, scroll into the field.
      // but you shouldn't chain if there are multiple fields.
      // this is annoying and repetitive because you always have
      // to specify the order of scrolling.
      // check the advanced method above
    	if (this.errors.has('email')) {
      	this.$refs.emailInput.focus();
      } else if (this.errors.has('name')) {
      	this.$refs.nameInput.focus();
      }
    },
  	validate (advanced) {
    	this.$validator.validate().then(result => {
      	if (!result) {
        alert('1')
        	if (advanced) {
          alert('2')
            return this.handleValidationErrorBasic();
          }
          
          return this.handleValidationErrorAdvanced();
        }
        
        
        // submit or something
      });
    }
  }
});