views:

199

answers:

5

I need to make it so a user can ONLY type a-z0-9 into my input box. How can I make it so the user simply cannot type other characters? If this isn't possible, how can I simply check the input with regex?

Thanks!

+2  A: 

If you use jQuery, there is a format plugin that does exactly what you need. Other than that, you can use onkeyup/onkeyup to call function which will validate input against regex pattern.

Krule
Looks good, I'll give it a shot
Cyclone
+1  A: 

You can use the onKeyDown event. If you return false from your event handler, no key press event is fired and the key is "eaten".

Here are the docs from Sun: http://docs.sun.com/source/816-6408-10/handlers.htm#1120313

Moishe
+1  A: 

Another notable solution is this alphanumeric plugin for jquery: http://itgroup.com.ph/alphanumeric/

Simple as $('#textField').alphanumeric();

Brandon G
A: 

Make sure you also perform the validation on the server too (assuming there's a server part to this) in case some users have javascript turned off.

Matthew Lock
+1  A: 

Here is a solution that's adapted a bit from this page:

window.onload = function () {
    document.forms.myForm.myField.onkeypress = keyTest;
}

function keyTest(e) 
{
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromCharCode(key);
    reg = /[a-z0-9]/i;

    if (key != 8 && key != 9) return reg.test(keychar);
}
ptrin