You can listen for keydown
/keypress
, check the character code, and if it's not something you want preventDefault()
or return false
Implementation
Here's an example with jQuery. This creates a list of 'valid' keycodes, initially populated with formatters (Escape, Backspace etc) and then populates the array with other valid keys.
$('input').keydown(function(e) {
var a=[8,9,13,16,17,18,20,27,35,36,37,38,39,40,45,46,91,92];
var k = e.which;
for (i = 48; i < 58; i++) // 0-9 on top of keyboard
a.push(i);
for (i = 65; i < 91; i++) // a-z
a.push(i);
for (i = 96; i < 106; i++) // 0-9 on numpad
a.push(i);
if (!(a.indexOf(k)>=0)) // prevents disabled keys
e.preventDefault();
});
You can also use this array to check validity of the username before submitting, by iterating through each character in the string and making sure it's one of these.
Try it out here
http://jsfiddle.net/vRJ2v/