views:

42

answers:

4
$(function(){
    $('input[name="username"]').keydown(function(key){
        if (jQuery.inArray(key.keyCode, 
            [8,37,39,48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90])
             == -1 || key.shiftKey ){
                return false;
        }
    });
});

What this does is Ajax validation on the text characters, it only lets me enter letters from a-z and 0-9, and not any other characters, but i want it to allow me the _ (underscore) character as well.

A: 

Check for both keyCode and shiftKey:

(key.shiftKey && key.keyCode == 109)

As others mention, if you need strict validation on the client side, you need to do more than just handle the keydown event.

Larsenal
189 is the IE key code; jQuery normalizes `event.which`, which gets code 109 assigned. See [.keydown()](http://api.jquery.com/keydown/).
Marcel Korpel
A: 

Add code 27 to the array?

Satyajit
27? Where did you get that 27 from?
Marcel Korpel
nope it deosnt work
getaway
+2  A: 

A slightly more readable way of doing that is

$('input[name="username"]').keydown(function() {
    $(this).val($(this).val().replace(/[^a-zA-Z0-9_]/g, ''));
});

Also note that validating on keydown events will not stop someone from copy/pasting any txt with the mouse.

Tgr
that deost work sorry mate
getaway
thanks, but it still let me enter illegal characters, i only want a-z 0-9 and the underscore
getaway
+2  A: 
$('input[name="username"]').keypress(function(event) {
  var k = event.which;
  /* 0:      non-input keys
     8:      backspace
     48-57:  0-9
     97-122: a-z
     95:     _ */
  if (k != 0 && k != 8 && k != 95 &&
      (k < 48 || k > 57) && (k < 97 || k > 122))
    return false;
});

$('input[name="username"]').keyup(function() {
  var inp = $(this).val();

  if (inp.match(/[^a-z0-9_]/g))
    $(this).val(inp.replace(/[^a-z0-9_]/g, ''));
});

The keypress event handler tries to catch invalid characters before they are input into the field, to prevent a distracting 'jumping' effect when invalid characters are shown and on keyup are removed again. Note that event.which contains the character code, normalized by jQuery.

The keyup handler is necessary to catch characters that are input using Ctrl-V (note that it unfortunately doesn't catch input using the menu option Edit > Paste). The extra test is necessary to stop the input field from getting back to its most left position after every keyup (caused by changing its value). Now it only resets its position when there is something to be removed.

You can test it on JSBin.

Marcel Korpel
This is the best answer given the need for the underscore, shift key, the keydown and keypress, normalization and all that jazz :)
Mark Schultheiss
Modern browsers have a paste event, which fires too early, but you can use setTimeout with zero delay from inside the event handler to catch pasting by mouse.
Tgr