Mujahed AKAS Mujahed AKAS - 5 months ago 6x
Javascript Question

How to prevent user from entering specific keys in chrome?

I have used following jQuery function to prevent user from entering specific keys,

$('#prod_name_en').keypress(function (e) {
if (e.key.match(/[!@#]+/))

It is working fine in mozilla but not in chrome.

it is throwing following error,

Uncaught TypeError: Cannot read property 'match' of undefined

Please help me how to resolve this issue.


Don't rely on JQuery's keyboard event key property. It may not work as we expected.
There are two different types of codes: keyboard codes(a number representing the key on the keyboard the user pressed) and character codes(a number representing a Unicode character). IE only stores the character code in keyCode while all other browsers store it in which. Some(but not all) browsers also store it in charCode and/or keyCode.
To get character value - use the character code through the String.formCharCode method:

$('#prod_name_en').on('keypress', function(e){
    var keyCode = e.keyCode || e.charCode || e.which; // cross-browser key-code detection
    if (String.fromCharCode(keyCode).match(/[!@#]+/)) e.preventDefault();