简体   繁体   中英

How to allow all characters but number from input

At the moment, I have an input. I am allowed to enter any characters, even special characters, no digits.

What I've tried so far is to setup a keydown and a keyup event.

ng-keydown="vm.preventNumberInput($event)"
ng-onkeyup="vm.preventNumberInput($event)"

vm.preventNumberInput = function (e) {
    var keyCode = (e.keyCode ? e.keyCode : e.which);
    if (keyCode > 47 && keyCode < 58 || keyCode > 95 && keyCode < 107) {
        e.preventDefault();
    }
}

This works okay, but it prevents me from adding special characters like.@#%^&*.

May I ask how do I allow characters from being entered into my input that aren't digits.

Check the event's key property to get the pressed key. If it matches \d (a digit), call preventDefault :

vm.preventNumberInput = function (e) {
    if (/\d/.test(e.key)) {
        e.preventDefault();
    }
}

Any characters other than digits will be allowed.

(note that the keyCode and which properties are deprecated, and should be avoided when possible)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM