0

I borrowed a bit of code from this question (see reply 4):

how do i block or restrict special characters from input fields with jquery?

However, upon using the code, it appears, that although it does the validation as you type neatly, it does not allow you to edit anything you have entered.

$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
   event.preventDefault();
   return false;
}});

I am a bit confused, I have tried to adjust it by changing the keypress to keyup but this just stops the validation from working. Any pointers would be graciously accepted.

Community
  • 1
  • 1
Bernie Davies
  • 419
  • 6
  • 15

2 Answers2

1

This seems to be a browser specific issue. In Firefox keypress includes meta keys like backspace and the arrow keys while Chrome does not. If you adjust your logic a bit to prefer which over charCode (which I think is better supported anyways) you end up with this

$('input').bind('keypress', function(event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var code = event.charCode === 0 ? event.which : event.charCode;
    var key = String.fromCharCode(code);
    if (!regex.test(key) && code !== 8) {
         // 8 is ascii code for backspace
         event.preventDefault();
         return false;
    }
});

This fiddle also writes to console the keys and codes being passed in the event when typing. http://jsfiddle.net/Q2MWS/5/

JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
  • Thank you JaredMcAteer, that works just lovely - greatly appreciated. Although I now have to figure out how to handle pasted input. – Bernie Davies May 30 '12 at 19:26
  • @BernieDavies There is an `onpaste` event you can hook into and validate the text pasted. http://stackoverflow.com/questions/1601353/detect-paste-on-input-box – JaredMcAteer May 30 '12 at 19:37
0

I think event.preventDefault() is preventing editing of entered chars if they are not matching the regexp. Check event.which/event.charCode for other values like backspace, space, decimal-point-key etc

rt2800
  • 3,045
  • 2
  • 19
  • 26
  • Hmm, just read the event.which stuff on jquery docs and it is a bit confusing. I think I might revert to a more standard approach unless anyone has any other suggestions. Thank you for the reply though. Appreciated. – Bernie Davies May 30 '12 at 16:20