I want to verify and validate the password in a form in HTML, and insert alerts in Front if necessary ("eg. Password not long enough"), which will serve as a "new user" form for a website. I want to start by understanding my mistake for the "password" verification and validation, and then validate the form once everything is correct.
I currently have the following in HTML:
<form id="formNouveau">
<div>
<div id="msgPseudo"></div>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<div id="msgEmail"></div>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" required>
</div>
<div>
<div id="msgPass"></div>
<label for="password">Mot de passe</label>
<br>
<input type="password" name="password" id="password" placeholder="*******" required>
</div>
<div>
<div id="msgPassRep"></div>
<label for="passwordRepeat">Repeat your password</label>
<br>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="*******" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
and the code in JS, with a focus on the password verification and validation:
function valideForm(e) {
e.preventDefault();
var valPassword = document.getElementById("password").value;
if((valPassword.length < 8)) {
alert("Password should be at least 8 characters")
}
else if((valPassword.length > 30)) {
alert("Password should not exceed 30 characters")
}
else if (!/[A-Z]/.test(valPassword)) {
alert("Password should have at least 1 uppercase")
}
else if (!/[a-z]/.test(valPassword)) {
alert("Password should have at least 1 lowercase")
}
else if (!/[0-9]/.test(valPassword)) {
alert("Password should have at least 1 number")
}
else if (!/(?=.[$#%£&§@])/.test(valPassword)) {
alert("Password should have at least 1 special character")
}
else {
alert("Password is correct");
return false;
}
}
document.getElementsByTagName('form')[0].addEventListener('submit', valideForm);
The alert messages appear only when the previous alert was displayed, and not all together. For example I will be missing an uppercase and a special character in my password, the alert will only display "Password should have at least 1 uppercase". Once I have added the uppercase, then will the other alert display "Password should have at least 1 special character."
What do you think?
Thank you!