4

I'm using regex to only allow letters, numbers and dot (.)

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

jsFiddle

However, one can still insert characters like ", é, ~e, #, $, etc. So i mean characters you type with the Shift key.

Also, typing characters using alt+1234 for example are still allowed.

Is there a way to prevent this on the keydown event of an input?

RobinvdA
  • 1,313
  • 2
  • 13
  • 28
  • Pretty much the same as http://stackoverflow.com/a/10866473/, which also faces the same problem. – fedorqui Dec 31 '14 at 11:24
  • @M42 I use \b to allow backspace. The regex works fine, but it still allows a lot of special characters. I think this is more of a javascript issue than a regex issue. – RobinvdA Dec 31 '14 at 11:31
  • Use keypress instead keydown to prevent ALT+1... – axel.michel Dec 31 '14 at 11:55

1 Answers1

5

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character.

Therefore, to avoid SHIFT + KEY, ALT+ KEY, use keypress not keydown

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

fiddle is here

axel.michel
  • 5,764
  • 1
  • 15
  • 25