I want to accept only letters, numbers, and commas in an input.
I have tried
document.getElementById('input').onkeydown = function (e) {
const charCode = (typeof e.which === 'number') ? e.which : e.keyCode;
return (charCode >= 48 && charCode <= 57) || // numbers
(charCode >= 65 && charCode <= 90) || // letters
charCode === 188 // comma
};
It works, but it also rejects using the arrow keys, enter, delete, and backspace (and potentially other important keys).
I could add another or
clause and tell if the user pressed a key arrow, enter, delete or backspace, but is this the correct way to do it? Am I missing some keys? Are the key codes the same on both tablet, desktop and smartphone?
Edit
What if I also want to make sure the user never inputs two consecutive commas? So it won't accept a,b,,c
?