Spread the love

In this tutorial, we will cover password strength validation , password not empty validation and confirm password validation. we will check on every submission of form whether the entered password pass or fail the criteria.

Password Strength validation in javascript

Password field must contain

  1. At least 8 characters
  2. Should be alphanumeric
  3. Should not be empty

index.html

<form name="registerform" onsubmit="return onSubmitHandle()">
              <div class="form-group">
                <label>Password</label>
                <input
                  type="password"
                  name="password"
                  id="password"
                  class="form-control"
                />
              </div>
              <div class="form-group">
                <label>Confirm Password</label>
                <input
                  type="password"
                  name="confirmPassword"
                  class="form-control"
                />
              </div>
              <div id="error" style="color: red"></div>
              <div class="form-group">
                <input type="submit" value="Submit" />
              </div>
            </form>

Script for validation

function getElement(id) {
      return document.getElementById(id).value;
    }

    function onSubmitHandle() {
      var isFormValid = true;
      var pass = document.getElementById('password').value;
      var err_elmt = document.getElementById('error');

      if (pass == '') {
        err_elmt.innerHTML = 'Please enter password';
        isFormValid = false;
      } else if (pass.length < 8) {.  // check password is 8 char long
        err_elmt.innerHTML = 'Please must be at least 8 char long';
        isFormValid = false;
      } else if (!(/\d/.test(pass) && /[a-zA-Z]/.test(pass))) {. // check password contains atlease one char and digit
        err_elmt.innerHTML = 'Please enter at least 1 char and 1 number';
        isFormValid = false;
      } else {
        err_elmt.innerHTML = '';
      }

      return isFormValid;
    }

Here, we are using char length and regex to validate the string.

Check string contains atleast a character and one digit

!(/\d/.test("test1234") && /[a-zA-Z]/.test("Test1234"))

here, we are checking digit and string capital and lower case both.

Next , we are going to check password and confirm password. we will add new condition

else if (confirm_pass!=pass){ err_elmt.innerHTML = 'Password and confirm password does not match'; isFormValid = false; }

Screenshot

Leave a Reply