Reputation: 18295
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!
Upvotes: 2
Views: 1357
Reputation: 2206
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);
}
Upvotes: 1
Reputation: 13486
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.
Upvotes: 0
Reputation: 2893
Another notable solution is this alphanumeric plugin for jquery: http://itgroup.com.ph/alphanumeric/
Simple as $('#textField').alphanumeric();
Upvotes: 2
Reputation: 8471
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
Upvotes: 1
Reputation: 6476
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.
Upvotes: 2