Skip to content

Instantly share code, notes, and snippets.

@PiotrKrzyzek
Last active November 11, 2019 16:24
Show Gist options
  • Save PiotrKrzyzek/f28ea20c880b71ec3c51523caaf38ea3 to your computer and use it in GitHub Desktop.
Save PiotrKrzyzek/f28ea20c880b71ec3c51523caaf38ea3 to your computer and use it in GitHub Desktop.
Restrict special characters with javascript / jQuery
<script>
$(document).ready(function() {
$('textarea').bind('keypress', function (event) {
// Allow for regular characters and include these special few:
// comma, period, explanation point, new line
var regex = new RegExp("^[a-zA-Z0-9\r\n\.\,\!\ ]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment