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.
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)
}
})
}
})
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()
}
})
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With