I was trying to restrict a form’s field from only allowing the user to enter alphanumeric characters into it. I looked all around and couldn’t find a nice way to do it without a plugin, so I wrote my own bind function that you can attach straight to an element.

[code lang=”javascript”]
$(“#yourFieldsElementId”).bind(“keypress”, function (event) {
if (event.charCode!=0) {
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;
}
}
});
[/code]

If you would like to restrict the input to only be numeric then do this:
[code lang=”javascript”]
$(“#yourFieldsElementId”).bind(“keypress”, function (event) {
if (event.charCode!=0) {
var regex = new RegExp(“^[0-9]+$”);
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
});
[/code]

If you would like to restrict the input to only be alphabetical then do this:
[code lang=”javascript”]
$(“#yourFieldsElementId”).bind(“keypress”, function (event) {
if (event.charCode!=0) {
var regex = new RegExp(“^[a-zA-Z]+$”);
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
});
[/code]

If you’re wondering about the following line:
[code lang=”javascript”]
if (event.charCode!=0) {
[/code]

It is there to double check that if the delete or backspace key is pressed.
If you don’t have this check then you cannot delete data.