2

I'm using VueRouter to make a single page application and VeeValidate for validation. I want to add a method that checks the status of valid inputs on a page in order to determine whether or not to progress.

An input would look like this:

<input 
  type="text"
  class="ze-input"
  placeholder="Enter mobile number"
  v-validate="'required'" 
  :class="{'input': true, 'is-danger': errors.has('mobile number') }" 
  name="mobile number"
>

I use a router-link to progress with the router:

<router-link to="send_to_hospital" class="col-sm-12 navigation ze-button">
  Next
</router-link>

How can I validate the page when the router-link is clicked and stop progression if the validation fails?


My routing configuration file:

import Vue from 'vue'
import Router from 'vue-router'
import HowCanWeHelpYou from '@/components/how_can_we_help_you'
import AboutSelf from '@/components/about_self'
import AppointmentInfo from '@/components/appointment_info'
import ContactUs from '@/components/contact_us'
import SendToHospital from '@/components/send_to_hospital'
import Confirmed from '@/components/confirmed'

import VeeValidate from 'vee-validate'
import vmodal from 'vue-js-modal'

Vue.use(VeeValidate)
Vue.use(vmodal)

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: '/',
      component: HowCanWeHelpYou
    },
    {
      path: '/about_self',
      name: 'about_self',
      component: AboutSelf
    },
    {
      path: '/appointment_info',
      name: 'appointment_info',
      component: AppointmentInfo
    },
    {
      path: '/contact_us',
      name: 'contact_us',
      component: ContactUs
    },
    {
      path: '/send_to_hospital',
      name: 'send_to_hospital',
      component: SendToHospital
    },
    {
      path: '/confirmed',
      name: 'confirmed',
      component: Confirmed
    }
  ]
})

1 Answer 1

1

Vue Router allows you to set Navigation Guards in a few different places. These guards are hooks wherein you can validate the fields when the route changes and then prevent the change if any fields are invalid.

It would probably make the most sense to add a beforeRouteLeave guard to the component which contains the fields:

beforeRouteLeave(to, from, next) {
  // Tells VeeValidate to validate all the fields in the component's scope
  this.$validator.validateAll(); 

  if (!this.errors.any()) { // if there are no errors
    next(); // go to the next route
  }

  // otherwise, next() doesn't get called and the route doesn't change
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.