javascriptvue.jsvuejs2

Input Field Only Accepting Numeric Value Using Directive In Vue.js


I am new to Vue.js. I want an input field which accepts only numeric numbers and if the user enters any other value it will be replace with the empty string. Therefore, I want to add a custom directive to this field viz 'numericOnly'.

Code for custom directive :

Vue.directive('numericOnly', {
  bind (el, binding, vnode) {
    regex = /^[0-9]*$/
    if(!regex.test(el.value)){
     el.value = el.value.slice(0, -1)
    }
  }
})

Here is my template :

<input v-numericOnly name="mobileNumber" placeholder="Mobile Number" >

But it runs only the one time when the input field is bound to the DOM.

Please help me figure out this problem. Thank you in advance.


Solution

  • Your directive should listen keyup of the input element to achieve what you need:

    Vue.directive('numericOnly', {
      bind(el) {
        el.addEventListener('keyup', () => {
          let regex = /^[0-9]*$/
          if (!regex.test(el.value)) {
            el.value = el.value.slice(0, -1)
          }
        })
      }
    })