Validate input text on keyup with jQuery

Want to validate an input excluding special characters?

It's unbelievably easy with JavaScript, well actually this example is done with jQuery.

The code below will remove the non-valid characters as you type them. Alternatively you could prompt an alert message on the callback function (right now returns nothing).

// Run the code when the page is complete
$(document).ready(function () {
  // Attach the event handler for the keyboard keyup
  $('input').keyup(function () {
    var $th = $(this);
    // run the expression and replace with nothing
    $th.val($th.val().replace(/[^a-zA-Z0-9]/g, function () {
      return '';
    }));
  });
});

Demo

View Demo

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.
One comment

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*