Validate child input components on submit with Vee-Validate

For plain Vuejs i use:

inject: ['$validator'],

in the child,

and:

provide() {
   return {
     $validator: this.$validator,
   };
},

in the parent.


I have a similar setup, I tried the bus solution with the events, didn't get it working. I however used the Provider/Injector pattern as defined in the specs of v-validate.

So in the top most parent, add this line of code (mind it is TYPESCRIPT !)

 @Provide('validator') $validator = this.$validator;

And in every child/grandchilds add this line of code:

@Inject('validator') $validator: any;

Now you can do this in your parent, and I will gather all errors from all components with the validator injector. (see specs: https://baianat.github.io/vee-validate/api/errorbag.html#api)

 if (this.$validator.errors.any()) {
      // Prevent the form from submitting
      e.preventDefault();
    }

I have a sort-a-like answer in post; vee-validate error object - _vm.errors is undefined

grtz


I'm not sure I understand you correctly. But to make the call globally, you will have to emit an event on clicking the button and instruct each template to act upon that event. The action for each template should be to 'this.$validator.validateAll()', because 'this' will refer to that specific template.

You can do that by creating a named instance ('bus'). Create that before creating the instance.

var bus = new Vue({});

Use that to emit from the template:

bus.$emit('validate_all');

and to catch in a template:

created: function() {
   var vm = this;
   bus.$on('validate_all', function() {
      vm.$validator.validateAll()
   });
}

Now all fields should have been validated and all error messages should show. Good Luck!

Tags:

Vue.Js