Mohamed.S
Mohamed.S

Reputation: 11

Why is my onsubmit validation function not submitting my function?

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>

My function works when it's false but when all the conditions are satisfied it doesn't submit the function.

Upvotes: 0

Views: 40

Answers (1)

Quentin
Quentin

Reputation: 943217

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.

Upvotes: 3

Related Questions