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

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, ''); }) } });

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 ''; })); }); });

Demo

View Demo

One comment

Leave a Reply

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

*
*