how do i block or restrict special characters from input fields with jquery?

Nerd Stalker picture Nerd Stalker · May 22, 2009 · Viewed 317.9k times · Source

How do I block special characters from being typed into an input field with jquery?

Answer

Dale picture Dale · Jan 12, 2012

A simple example using a regular expression which you could change to allow/disallow whatever you like.

$('input').on('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;
    }
});