Validate input text on keyup with JavaScript

Want to validate an input excluding special characters?

It's unbelievably easy with JavaScript.

If you need to do it with jQuery, scroll down.

The code below will remove/sanitize the non-valid characters as the user types them.

HTML

<input class="my-input" type="text" />Code language: JavaScript (javascript)

JavaScript

document.addEventListener("DOMContentLoaded", function () {
  const $input = document.querySelector('.my-input');

  if ($input) {
    $input.addEventListener('keyup', () => {
      $input.value = $input.value.replace(/[^a-zA-Z0-9]/g, '');
    })
  }
});Code language: PHP (php)

jQuery

// Run the code when the page is complete
$(document).ready(function () {
  // Attach the event handler for the keyboard keyup
  $('.my-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 '';
    }));
  });
});Code language: JavaScript (javascript)

Demo

View Demo

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *