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.


<input class="my-input" type="text" />
Code language: 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)


// 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)


View Demo

About Ricard Torres

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

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast


Leave a Reply

Add <code> Some Code </code> if you need to.