How do I not allow the user to enter special characters such as *-/+.,:;[]{}ªº^~?<>
into the question field?
How do I not allow the user to enter special characters such as *-/+.,:;[]{}ªº^~?<>
into the question field?
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.
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" />
Use the patterns for HTML 5.
Example:
<input type="text" pattern="^[a-zA-Z0-9]+$" />