2

Does somebody knows how to implement a VUE input field that rejects entering non digits as the user tries to enter it.

Some kind of:

<b-form-input v-on:keypress="onlyNumber(...."

Thanks!

JLLMNCHR
  • 1,551
  • 5
  • 24
  • 50

3 Answers3

1

The easiest way would be to declare the input type to number. <b-form-input type="number" ...

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
1

Finally, for me, this do the job:

    <input v-on:keydown="onlyNumber($event)" ... />

    

onlyNumber: function(evt) { //0035621
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57))) {
            evt.preventDefault();
        } else {
            return true;
        }
    }
JLLMNCHR
  • 1,551
  • 5
  • 24
  • 50
0

You can use keyCode of the key pressed on keydown event and perevent default behavior if keyCode isn't for a non digit key;

Vue input component:

<b-form-input @keydown="onlyNumbers" />

And the onlyNumbers method would be:

onlyNumbers(e) {
    if((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
}

Related Links: keyCode values for numeric keypad, preventDefault, Keydown Event

mo3n
  • 1,522
  • 2
  • 10
  • 34
  • Thanks, but, onlyNumbers is not called (¿?) – JLLMNCHR Dec 21 '21 at 10:56
  • onlyNumbers would be placed in the methods section of the parent component of and it would be called every time that emits a keydown event. – mo3n Dec 21 '21 at 11:00
  • @keydown.native? – Peter Dec 21 '21 at 11:10
  • This should work too, but since '.native' is removed in Vue3, it would be better to emit the event from input component. – mo3n Dec 21 '21 at 11:18
  • https://v3.vuejs.org/guide/migration/v-on-native-modifier-removed.html#overview – mo3n Dec 21 '21 at 11:19
  • As Maik Lowery said in the following answer, another solution is to use an input with type number, and if you don't want the arrows that comes with it, you can easily hide them using css. – mo3n Dec 21 '21 at 11:22