Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 254
Pulkit Aggarwal Avatar asked Feb 09 '18 07:02

Pulkit Aggarwal


2 Answers

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)
      }
    })
  }
})
like image 56
Bob Dust Avatar answered Oct 21 '22 14:10

Bob Dust


import Vue from 'vue'    
Vue.directive('numericOnly', {
bind(el, binding, vnode) {
    el.addEventListener('keydown', (e) => {
        if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
            // Allow: Ctrl+A
            (e.keyCode === 65 && e.ctrlKey === true) ||
            // Allow: Ctrl+C
            (e.keyCode === 67 && e.ctrlKey === true) ||
            // Allow: Ctrl+X
            (e.keyCode === 88 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
            // let it happen, don't do anything
            return
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault()
        }
    })
}

})

like image 43
Anas Rezk Avatar answered Oct 21 '22 14:10

Anas Rezk