0

I was wondering which is the best practise to trigger input validation in Vue JS, using events such as onchange, keyup or having watchers on each property? Let`s assume that you only have around 20 inputs to deal with.

Sugafree
  • 631
  • 2
  • 14
  • 30

1 Answers1

0

As you said you might have n number of inputs in your form on which you want to add validation. I think watcher is a good feature to use as it will update every time any changes happen in the form data.

In your data object, You can create one formData object which will contain all the input field properties and then you can put a watcher on formData.

Live Demo :

var App = new Vue({
  el: '#app',
  data() {
    return {
      formData: {
        name: 'Alpha',
        age: 30
      }
    }
  },
  watch: {
    'formData': {
      deep: true,
      handler(val) {
        console.log(val)
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <form>
    <label for="name">Name
      <input id="name" type="text" v-model="formData.name">
    </label>Age
    <label for="age">
      <input id="age" type="number" v-model="formData.age">  
    </label>
  </form>
</div>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • 1
    Definetely the watch property when your entire formdata can be represented as a single nested property. But this can hurt performance too for large formdata, and can cause unnecessary validation for unchanged form inputs. I would suggest adding a debounce too. – Blaine Sep 19 '22 at 08:20
  • @Blaine what do you mean by debounce and at what size of a form would you say watch could hurt performance? – Sugafree Sep 19 '22 at 08:25
  • @Sugafree well see anytime you update anything in the form data, the change value will be called and since its the entire form data all form fields will be validated at once. Now the watch function will also run on every keystroke, so the idea is to wait for the user to stop typing to validate the input. Effectively debouncing. Check this https://stackoverflow.com/questions/45178621/how-to-correctly-use-vue-js-watch-with-lodash-debounce – Blaine Sep 22 '22 at 01:19
  • @Blaine implementation will totally depend on the type of validations required by the PO. If he wants to validate the input on every character press then denounce will not work here. – Debug Diva Sep 22 '22 at 03:55
  • Thats why whatever I said was in the format of a comment, its a thing to keep in mind when working on validation. – Blaine Sep 22 '22 at 17:38