Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save csharpforevermore/6069458 to your computer and use it in GitHub Desktop.
Save csharpforevermore/6069458 to your computer and use it in GitHub Desktop.
User can only enter letters and digits in a input text box Original code is from: http://stackoverflow.com/questions/895659/how-do-i-block-or-restrict-special-characters-from-input-fields-with-jquery
$('input').bind('keypress', function (event) {
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;
}
});
@harshil82
Copy link

this isn't working

@mohammadhzp
Copy link

worked for me, I used keydown though and didn't use bind(used old style)

@FerrarisIV
Copy link

FerrarisIV commented Jul 6, 2018

Thanks, it is working for me. How can I also add the ability to press "Enter" ?

EDIT
Solved: I added \r\n like this
var regex = new RegExp("^[a-zA-Z0-9\r\n]+$");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment