8

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.

3 Answers 3

11

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)
      }
    })
  }
})
Sign up to request clarification or add additional context in comments.

4 Comments

Say some thing about your code how it answer the op Question?
@ShreeKhanal, I added a bit :)
Thank you @BobDust. We have to removeListner on unbind in this case.
v-model on this element is not getting updated in this case.
6
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()
        }
    })
}

})

3 Comments

prevent user from writing character in textbox only allow numbers for example if you have a textbox for age and want user to write only number
a working example for demonstrate the code above jsfiddle.net/AnasRezk/roLtf9wq
you can type in 1.......... or .........., so not really a solution. or 1.1.1.1.1..1
0

Updated on Nov 26th 2024:

The event.keyCode property is deprecated

We should use event.key or event.code

// directives/numeric-only.js
export default {
  bind(el) {
    el.addEventListener('keydown', function (event) {
      // Allow control keys such as backspace, delete, arrows, etc.
      if (
        event.key === 'Backspace' ||
        event.key === 'Delete' ||
        event.key === 'ArrowLeft' ||
        event.key === 'ArrowRight' ||
        event.key === 'Tab' ||
        event.key === 'Enter' ||
        (event.ctrlKey && event.key === 'a') || // Allow Ctrl+A (Select All)
        (event.ctrlKey && event.key === 'c') || // Allow Ctrl+C (Copy)
        (event.ctrlKey && event.key === 'v') || // Allow Ctrl+V (Paste)
        (event.ctrlKey && event.key === 'x') // Allow Ctrl+X (Cut)
      ) {
        return; // Do not prevent default for these keys
      }

      // Allow numeric characters only
      if (!/^[0-9]$/.test(event.key)) {
        event.preventDefault(); // Prevent input if not a numeric character
      }
    });
  }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.