How to Restrict Special Characters in an Input Textbox using JavaScript?

If you want to restrict the user to enter special characters in an input textbox, you can do it in the following steps:

  • Add an Id to the input element using the id attribute eg. id=”myInput”.
  • Get the input element using the getElementById() method.
  • Listen to the keypress event for this input box using the addEventListener() method.
  • Check if the key pressed by the user is a special character or not. If yes, restrict it using the event.preventDefault() method.

Let’s say we have the following text input in our HTML document with an id="myInput":

<input type="text" id="myInput" placeholder="Type something">

Now, check the key code of the pressed key. If it doesn’t lie in the below range, it’s an special character, restrict it:

  • 97 – 122 (a – z)
  • 65 – 90 (A – Z)
  • 48 – 57 (0 – 9)

Here is the implementation of all the above steps in JavaScript. This will not allow you to enter any special character in the textbox.

// Get the text input
const input = document.getElementById('myInput');

// Add keypress event listener
input.addEventListener('keypress', function(event){
    
    // Get the key code
    let keycode = event.which || event.keyCode;
    
    // Check if key pressed is a special character
    if(keycode < 48 || 
     (keycode > 57 && keycode < 65) || 
     (keycode > 90 && keycode < 97) ||
     keycode > 122
    ){
        // Restrict the special characters
        event.preventDefault();  
        return false;
    }
});  

Method 2 – Using Regular Expression

You can also use regular expressions to restrict the user to enter special characters in the input textbox.

You simply need to check if the key pressed by the user matches the regular expression using the test() method. The test() method returns true if key/string matches the reg exp, otherwise, it returns false.

This is how you can do it in JavaScript:

// Get the text input
const input = document.getElementById('myInput');

// Add keypress event listener
input.addEventListener('keypress', function(event){
    
    // Get the key 
    let key = event.key;
    
    let regex = new RegExp("^[a-zA-Z0-9]+$");
    
    // Check if key is in the reg exp
    if(!regex.test(key)){
        
        // Restrict the special characters
        event.preventDefault();  
        return false;
    }
});

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.