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.
$("#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;
}
}
});
If you would like to restrict the input to only be numeric then do this:
$("#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;
}
}
});
If you would like to restrict the input to only be alphabetical then do this:
$("#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;
}
}
});
If you’re wondering about the following line:
if (event.charCode!=0) {
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.