0

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.

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Mohamed.S
  • 11
  • 2
  • Will it help you : https://stackoverflow.com/questions/5195933/with-form-validation-why-onsubmit-return-functionname-instead-of-onsubmit – Mani Nov 21 '21 at 12:59

1 Answers1

3

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335