javascript validation of the username and the password

function validateForm() {
  if (document.myForm.userName.value && document.myForm.password.value && document.myForm.confirmpassword.value) {
    if (document.myForm.password.value === document.myForm.confirmpassword.value) {
      if (document.myForm.userName.value.length < 3) {
        alert("Username length should be atleast 3 and make sure it starts with A-Z");
        return false;
      } else if (document.myForm.password.value.length < 8) {
        alert("Password must be at least 6 characters long.");
        return false;
      } else {
        if (new RegExp(/^[A-Za-z][A-Za-z0-9]+$/).test(document.myForm.userName.value) === false) {
          alert('Username begins with a character[a-zA-Z] ');
          return false;
        } else if (new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$@!%&*?])[A-Za-z\d#$@!%&*?]{8, 30}$ /).test(document.myForm.password.value)) {
          alert("password is 8 or more characters where at-least 1 uppercase letter And 1 number AND 1 of the special characters (/-+!@#$^&)");
          return false;
        } else {
          alert('Success !');
          return true;
        }
      }
    } else {
      alert("password & confirm password not match!");
      return false;
    }
  } else {
    alert("Please add valid credentials..");
    return false;
  }
}
<form name="myForm" action="main.html" method="post">
  <!--  onSubmit="return validateForm();" -->
  <label>User name</label><br />
  <input type="text" name="userName" placeholder="userName" />
  <br />
  <label>Password</label><br />
  <input type="password" name="password" placeholder="password" />
  <br />
  <label>Confirm Password</label><br />
  <input type="password" name="confirmpassword" placeholder="confirm password" />
  <br />
  <input type="button" value="Login" onclick='validateForm();' />
</form>

Note:- I have added all your points please let me know incase something went wrong!

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top