I have a form for the signup part of my code and using onsubmit I can validate client-side if the password is not long enough, etc. Here's my code:
function validate(e) {
e.preventDefault();
var pwd = document.getElementById("pwd").value;
if (pwd.length < 8) {
alert("Password not long enough");
return false;
} else if (pwd.search(/[a-z]/) < 0) {
alert("Your password needs a lowercase letter");
return false;
} else if (pwd.search(/[A-Z]/) < 0) {
alert("Your password needs an uppercase letter");
return false;
} else if (pwd.search(/[0-9]/) < 0) {
alert("Your password requires a number. ");
return false;
} else {
return true;
}
}
<form method="POST" onsubmit="return validate(event);">
<!-- Username and password text fields -->
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
My function works when it's false but when all the conditions are satisfied it doesn't submit the function.
CodePudding user response:
The default behaviour of the submit event is to submit the form.
e.preventDefault();
prevents the default behaviour.
You are calling it unconditionally. This makes the return value on the onsubmit
function irrelevant.