How to validate selected fields only with vee-validate

This is a tip on how to validate selected fields with vee-validate

How to validate selected fields only  with vee-validate

Form validation is one of the essensial part of creating your application. Doing it by hand takes time and you can forget other validation rules if you do it on your own. The time you will take working on a custom validation is better spent improving or doing other parts of application. 

Vee-validate is a form validation library for Vue.js that allows you to validate inputs and build better form UIs in a familiar declarative style or using composition functions.

See image below for example 

If you are using vee-validate("$validator.validateAll()" method) you may encounter an issue with validation that happens when you have 2 or more active components (modals) that have input fields (validated with vee-validate). It occurs when you sumbit one component (modal on the left) the validation rules for the other component (modal on the right) will also be triggered. Yes, you can just close your other component but if your task demands that both components are active you can validate only selected fields so that the validations (from the other component) will not be triggered.

Solution


You can use $validator.validate("input field name")  to specificy which input fields you want to validate. See the code bellow for example 

var results = [this.$validator.validate('field name'),this.$validator.validate('field name')];

In this example I stored the validations(array of promises) in results. After this you can use Promise.all() method to iterate all the promises(from $validate.validate("input field name")) from your array. Then you can check if there is an error (false) by include() method. 

Promise.all(results).then((values) => {
  if(!values.includes(false)){
    // DO SOMETHING IF THERE IS NO VALIDATION ERROR      
  }
  else{
    //  THERE IS VALIDATION ERROR
  }
});
Hope this helps.