I tried to insert this piece of code (which I had found on a website) on my (working) validation script:
if (register.username.match(/\W/)) {
alert('You have special characters on username field.');
return false;
}
It did nothing, and it also prevented the whole script from working.
This is the html form (not the whole thing):
<form name="register" method="POST" action="registar.php" onsubmit="return validateForm();">
<ul class="left-form">
<h2>Nova conta:</h2>
<li>
<input type="text" name="username" placeholder="Username" required/>
<div class="clear"> </div>
</li>
<li>
<input type="text" name="email" placeholder="Email" required/>
<div class="clear"> </div>
</li>
<li>
<input type="password" name="pass" placeholder="Password" required/>
<div class="clear"> </div>
</li>
<li>
<input type="password" name="pass_confirm" placeholder="Confirmar a password" required/>
<div class="clear"> </div>
</li>
<input type="submit" value="Registar">
<div class="clear"> </div>
</ul>
</form>
And this is my Javscript code (without the special characters checking):
function validateForm() {
if (register.username.value.length <= 2) {
alert("O username escolhido é demasiado curto.");
return false;
}
if (register.username.value.length > 20) {
alert("O username escolhido é demasiado longo.");
return false;
}
var x = register.email.value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("O email inserido parece ser inválido.");
return false;
}
if (register.username.value == register.pass.value) {
alert("Por questões de segurança, pedimos que use uma password diferente do seu nome de utilizador.");
return false;
}
if ((register.pass.value.length < 6) || (register.pass.value.length > 20)) {
alert("Certifique-se que a sua password tem entre 6 e 20 letras.");
return false;
}
if (register.pass.value != register.pass_confirm.value) {
alert("As passwords não condizem.");
return false;
}
return true;
}
Ignore the alerts as they are only the display messages.
Can someone write a piece of code which checks for special characters (! , . + * etc.) or tell me what's wrong with the code I used?