0

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.

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

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.