Special Characters Validation In Javascript With Regex

Special Characters Validation In Javascript
Table of Contents

Want to add special characters validation in javascript then today I will show you how to do special characters validation in javascript with regex we will do special characters validation with regex.

This will allow the user to only enter alphabets and numerics if they enter a special character they will be thrown an error message or an alert.

Here are some more Javascript Validation guides

Special Characters Validation In Javascript

Special characters validation in javascript is very easy and simple to do I will show you step by step how to do it so read this guide till the end.

				
					const form = document.getElementById('form')
const text = document.getElementById('text')

form.addEventListener('submit', (e) => {
    e.preventDefault()
    if (/[^a-zA-Z0-9\-\/]/.test(text.value)) {
        alert('Dont add special characters in the input');
        return false;
    }
    else {
        alert('Successfully validated')
    }
})
				
			

You need to add the above Javascript code in your JS file or in HTML things you need to note here is

  • Add ID to the form in your HTML
  • Add ID to the input in your HTML

This is an example of the input and form tags

				
					 <form id="form">
        <input type="text" id="text" required>
    </form>
				
			

You can test this code in our Online HTML Compiler and if you try to enter a special character it will alert you with a message you can show any message to the user.

If you want a video tutorial on this then you can watch this video for special character validation in regex javascript.

I have used regex for this validation I hope you found this guide useful and helpful if you want more guides like this do stay with us by

Thank you for reading, Have a nice day 🙂

Share This Post
Share on facebook
Share on twitter
Share on email
Share on whatsapp

Leave a Reply

Subscribe To Our Newsletter

Get updates and learn from the best

Latest Guides & Articles