'Detect printable keys

I need to detect whether the key which has just been pressed is a printable key, like a character, possibly accented, a number, a space, a punctuation symbol and so on, or a non printable key, like ENTER, TAB or DELETE.

Is there a reliable way to do this in Javascript, other than listing all non printable keys and hope not to forget some?



Solution 1:[1]

Luckily, this task is much easier in modern browsers. You can now use KeyboardEvent.key to detect a printable key via its length.

test.onkeydown = e => {
  let isPrintableKey = e.key.length === 1;
  alert(`Key '${e.key}' is printable: ${isPrintableKey}`);
}
<input id="test">

Besides that, you can also detect any other keys from the list, like Enter, Delete, Backspace, Tab, etc.

This method is much more reliable simply because unlike event.which, event.key is already standardized.

Solution 2:[2]

If you need to identify printable key just for change detection as user change the input, you could use oninput event.

Solution 3:[3]

let isPrintableKey = event.key.length === 1 || event.key === 'Unidentified';

If you do not include: || event.key === 'Unidentified' your code will not work on mobile browsers.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lewis
Solution 2 Downhillski
Solution 3 Lee Smith