JLLMNCHR
JLLMNCHR

Reputation: 1571

Rejecting non digits in vue input

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!

Upvotes: 2

Views: 502

Answers (3)

JLLMNCHR
JLLMNCHR

Reputation: 1571

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;
        }
    }

Upvotes: 1

mo3n
mo3n

Reputation: 1870

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

Upvotes: 0

Maik Lowrey
Maik Lowrey

Reputation: 17576

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

Upvotes: 1

Related Questions