How to block special characters in the field

10

How do I not allow the user to enter special characters such as *-/+.,:;[]{}ªº^~?<> into the question field?

    
asked by anonymous 08.10.2015 / 22:23

3 answers

12

If you want to do a simple validation only to assist the user in the client-side, you can use pattern .

It's an HTML5 attribute that's easy to tweak, here has some examples that solve your problem for example, enabling only letters, letters and numbers, etc.

Example for letters and numbers:

<input type="text" required="required" name="text" pattern="[a-zA-Z0-9]+">

And the best part is that it is supported by multiple browsers according to Can I use .

Now validating the data, I recommend you do it on the server-side . For example with PHP you can use preg_match :

$pattern = '[a-zA-Z0-9]';
if (preg_match($pattern, $email)){return true;}

You can go directly to:

if (preg_match("/([a-zA-Z0-9])/", $email)){return true;}

This will only accept letter and number characters.

    
08.10.2015 / 22:45
10

I did this, it will only allow letters and numbers:

       document.getElementById("teste").onkeypress = function(e) {
         var chr = String.fromCharCode(e.which);
         if ("1234567890qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM".indexOf(chr) < 0)
           return false;
       };
<input type="text" name="name" id="teste" />
    
08.10.2015 / 22:45
2

Use the patterns for HTML 5.

Example:

<input type="text" pattern="^[a-zA-Z0-9]+$" />
    
08.10.2015 / 22:44