Preventing characters such as quotation marks

I use regex only for letters, numbers and periods ( . )

$('input').on('keydown', function (e) {
    if (/^[a-zA-Z0-9\.\b]+$/.test(String.fromCharCode(e.keyCode))) {
        return;
    } else {
        e.preventDefault();
    }
});

jsFiddle

However, you can still insert characters like ", é, ~ e, #, $, etc. Therefore, I mean the characters that you enter with the Shift key.

In addition, you can still enter characters using alt + 1234.

Is there a way to prevent this from occurring on a keydown input event?

+4
source share
1 answer

, . keydown, . , , .

, SHIFT + KEY, ALT + KEY, keypress not keydown

$('input').on('keypress', function (e) {
    if (/^[a-zA-Z0-9\.\b]+$/.test(String.fromCharCode(e.keyCode))) {
        return;
    } else {
        e.preventDefault();
    }
}); 

+5

Source: https://habr.com/ru/post/1569533/


All Articles