Search code examples
htmlhtml-input

How do i stop anyone from entering these special characters characters?


Basically I don't want a user to input the following: (!@#$%^&*()_+[]{}';:".<>?) given that this is my code:

<div class = "form-item">
                    <label for = "Name">Name: </label>
                    <input type = "text" id = "Name" name="Cname">
                </div>

how do i do this? hopefully you can do it using the code given

We tried the regex on JavaScript but to be honest i don't understand it.


Solution

  • you don't really need regex. Just create a string of your special characters and loop through them each time the input is changed

    var sc = "(!@#$%^&*()_+[]{}';:\".<>?)"
    
    
    function test() {
    
      let input = document.getElementById('Name').value
      let last = input.substring(input.length - 1, input.length)
      
      for (i = 0; i < sc.length; i++) {
        if (last == sc.substring(i, i + 1)) document.getElementById('Name').value = input.substring(0, input.length - 1)
      }
    
    
    
    }
    <div class="form-item">
      <label for="Name">Name: </label>
      <input type="text" id="Name" name="Cname" oninput="test()">
    </div>