content logo

Bootstrap Forms:

Bootstrap Form with Check Password Strength While Typing

Passwords are the first line of defence and the most important one against hackers and data loss. Setting a proper password is essential in creating any account on any website. Usually, the stronger you make your password, the more powerful it becomes and can protect your account. Due to this reason, some websites use various methods to encourage you to make passwords harder to guess. For instance, they might tell you to use different symbols and a combination of uppercase and lowercase letters to strengthen your passwords. Generally, the harder your password it is to guess, the more protection value it possesses.

In this post, we are sharing a code for a check password form. This form looks like any other ordinary looking sign up Bootstrap form except it features a password validation system. You can set different parameters for the password – for instance, it has to contain a certain type of letters or symbols for it to be approved – to help maintain security. This is a great method to make sure everyone in your site uses complex and strong passwords. This Bootstrap password form is able to display the password strength via a line with the help of colours.

#

Password Strength

#

Check Password Form

#

Bootstrap Form

#

Bootstrap Password Form

<!-- This script got from frontendfreecode.com -->
<div class="content">
    <!--content inner-->
    <div class="content__inner">
        <div class="container">
            <div class="row">
                <div class="col-lg-6 m-auto">
                    <form class="password-strength form p-4">
                        <h3 class="form__title text-center mb-4">Enter the Password</h3>
                        <div class="form-group">
                            <label for="password-input">Password</label>
                            <div class="input-group">
                                <input class="password-strength__input form-control" type="password" id="password-input" aria-describedby="passwordHelp" placeholder="Enter password" />
                                <div class="input-group-append">
                                    <button class="password-strength__visibility btn btn-outline-secondary" type="button"><span class="password-strength__visibility-icon" data-visible="hidden"><i class="fas fa-eye-slash"></i></span><span class="password-strength__visibility-icon js-hidden" data-visible="visible"><i class="fas fa-eye"></i></span></button>
                                </div>
                            </div><small class="password-strength__error text-danger js-hidden">This symbol is not allowed!</small><small class="form-text text-muted mt-2" id="passwordHelp">Add 9 charachters or more, lowercase letters, uppercase letters, numbers and symbols to make the password really strong!</small>
                        </div>
                        <div class="password-strength__bar-block progress mb-4">
                            <div class="password-strength__bar progress-bar bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <button class="password-strength__submit btn btn-success d-flex m-auto" type="button" disabled="disabled">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div><a style="font-size: 8pt; text-decoration: none" target="_blank" href="http://frontendfreecode.com">Free Frontend</a>
                                                                            
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  font-family: "Muli", sans-serif;
  font-size: 16px;
  color: #2c2c2c;
}
body a {
  color: inherit;
  text-decoration: none;
}
.header__btn {
  transition-property: all;
  transition-duration: 0.2s;
  transition-timing-function: linear;
  transition-delay: 0s;
  padding: 10px 20px;
  display: inline-block;
  margin-right: 10px;
  background-color: #fff;
  border: 1px solid #2c2c2c;
  border-radius: 3px;
  cursor: pointer;
  outline: none;
}
.header__btn:last-child {
  margin-right: 0;
}
.header__btn:hover, .header__btn.js-active {
  color: #fff;
  background-color: #2c2c2c;
}
.header {
  max-width: 600px;
  margin: 50px auto;
  text-align: center;
}
.header__title {
  margin-bottom: 30px;
  font-size: 2.1rem;
}
.content {
  width: 95%;
  margin: 0 auto 50px;
}
.password-strength {
  box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.3);
}
.js-hidden {
  display: none;
}
DOM = {
  passwForm: '.password-strength',
  passwErrorMsg: '.password-strength__error',
  passwInput: document.querySelector('.password-strength__input'),
  passwVisibilityBtn: '.password-strength__visibility',
  passwVisibility_icon: '.password-strength__visibility-icon',
  strengthBar: document.querySelector('.password-strength__bar'),
  submitBtn: document.querySelector('.password-strength__submit') };
//*** HELPERS
//need to append classname with '.' symbol
const findParentNode = (elem, parentClass) => {
  parentClass = parentClass.slice(1, parentClass.length);
  while (true) {

    if (!elem.classList.contains(parentClass)) {
      elem = elem.parentNode;
    } else {
      return elem;
    }
  }
};
//*** MAIN CODE
const getPasswordVal = input => {
  return input.value;
};
const testPasswRegexp = (passw, regexp) => {

  return regexp.test(passw);

};
const testPassw = passw => {
  let strength = 'none';
  const moderate = /(?=.*[A-Z])(?=.*[a-z]).{5,}|(?=.*[\d])(?=.*[a-z]).{5,}|(?=.*[\d])(?=.*[A-Z])(?=.*[a-z]).{5,}/g;
  const strong = /(?=.*[A-Z])(?=.*[a-z])(?=.*[\d]).{7,}|(?=.*[\!@#$%^&*()\\[\]{}\-_+=~`|:;"'<>,./?])(?=.*[a-z])(?=.*[\d]).{7,}/g;
  const extraStrong = /(?=.*[A-Z])(?=.*[a-z])(?=.*[\d])(?=.*[\!@#$%^&*()\\[\]{}\-_+=~`|:;"'<>,./?]).{9,}/g;
  if (testPasswRegexp(passw, extraStrong)) {
    strength = 'extra';
  } else if (testPasswRegexp(passw, strong)) {
    strength = 'strong';
  } else if (testPasswRegexp(passw, moderate)) {
    strength = 'moderate';
  } else if (passw.length > 0) {
    strength = 'weak';
  }
  return strength;
};
const testPasswError = passw => {
  const errorSymbols = /\s/g;
  return testPasswRegexp(passw, errorSymbols);
};
const setStrengthBarValue = (bar, strength) => {
  let strengthValue;
  switch (strength) {
    case 'weak':
      strengthValue = 25;
      bar.setAttribute('aria-valuenow', strengthValue);
      break;
    case 'moderate':
      strengthValue = 50;
      bar.setAttribute('aria-valuenow', strengthValue);
      break;
    case 'strong':
      strengthValue = 75;
      bar.setAttribute('aria-valuenow', strengthValue);
      break;
    case 'extra':
      strengthValue = 100;
      bar.setAttribute('aria-valuenow', strengthValue);
      break;
    default:
      strengthValue = 0;
      bar.setAttribute('aria-valuenow', 0);}
  return strengthValue;
};
//also adds a text label based on styles
const setStrengthBarStyles = (bar, strengthValue) => {
  bar.style.width = `${strengthValue}%`;
  bar.classList.remove('bg-success', 'bg-info', 'bg-warning');
  switch (strengthValue) {
    case 25:
      bar.classList.add('bg-danger');
      bar.textContent = 'Weak';
      break;
    case 50:
      bar.classList.remove('bg-danger');
      bar.classList.add('bg-warning');
      bar.textContent = 'Moderate';
      break;
    case 75:
      bar.classList.remove('bg-danger');
      bar.classList.add('bg-info');
      bar.textContent = 'Strong';
      break;
    case 100:
      bar.classList.remove('bg-danger');
      bar.classList.add('bg-success');
      bar.textContent = 'Extra Strong';
      break;
    default:
      bar.classList.add('bg-danger');
      bar.textContent = '';
      bar.style.width = `0`;}
};
const setStrengthBar = (bar, strength) => {
  //setting value
  const strengthValue = setStrengthBarValue(bar, strength);
  //setting styles
  setStrengthBarStyles(bar, strengthValue);
};
const unblockSubmitBtn = (btn, strength) => {
  if (strength === 'none' || strength === 'weak') {
    btn.disabled = true;
  } else {
    btn.disabled = false;
  }
};
const findErrorMsg = input => {
  const passwForm = findParentNode(input, DOM.passwForm);
  return passwForm.querySelector(DOM.passwErrorMsg);
};
const showErrorMsg = input => {
  const errorMsg = findErrorMsg(input);
  errorMsg.classList.remove('js-hidden');
};
const hideErrorMsg = input => {
  const errorMsg = findErrorMsg(input);
  errorMsg.classList.add('js-hidden');
};
const passwordStrength = (input, strengthBar, btn) => {
  //getting password
  const passw = getPasswordVal(input);
  //check if there is an error
  const error = testPasswError(passw);
  if (error) {
    showErrorMsg(input);
  } else {
    //hide error messages
    hideErrorMsg(input);
    //finding strength
    const strength = testPassw(passw);
    //setting strength bar (value and styles)
    setStrengthBar(strengthBar, strength);
    //unblock submit btn only if password is moderate or stronger
    unblockSubmitBtn(btn, strength);
  }
};
const passwordVisible = passwField => {
  const passwType = passwField.getAttribute('type');
  let visibilityStatus;
  if (passwType === 'text') {
    passwField.setAttribute('type', 'password');
    visibilityStatus = 'hidden';
  } else {
    passwField.setAttribute('type', 'text');
    visibilityStatus = 'visible';
  }
  return visibilityStatus;
};
const changeVisibiltyBtnIcon = (btn, status) => {
  const hiddenPasswIcon = btn.querySelector(`${DOM.passwVisibility_icon}[data-visible="hidden"]`);
  const visibilePasswIcon = btn.querySelector(`${DOM.passwVisibility_icon}[data-visible="visible"]`);
  if (status === 'visible') {
    visibilePasswIcon.classList.remove('js-hidden');
    hiddenPasswIcon.classList.add('js-hidden');
  } else if (status === 'hidden') {
    visibilePasswIcon.classList.add('js-hidden');
    hiddenPasswIcon.classList.remove('js-hidden');
  }
};
const passwVisibilitySwitcher = (passwField, visibilityToggler) => {
  const visibilityStatus = passwordVisible(passwField);
  changeVisibiltyBtnIcon(visibilityToggler, visibilityStatus);
};
//*** EVENT LISTENERS
DOM.passwInput.addEventListener('input', () => {
  passwordStrength(DOM.passwInput, DOM.strengthBar, DOM.submitBtn);
});
const passwVisibilityBtn = document.querySelector(DOM.passwVisibilityBtn);
passwVisibilityBtn.addEventListener('click', e => {
  let toggler = findParentNode(e.target, DOM.passwVisibilityBtn);
  passwVisibilitySwitcher(DOM.passwInput, toggler);
});
<link href="https://fonts.googleapis.com/css?family=Muli:400,600&display=swap" rel="stylesheet">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js'></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- This script got from frontendfreecode.com -->

<link href="https://fonts.googleapis.com/css?family=Muli:400,600&display=swap" rel="stylesheet">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js'></script>
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  font-family: "Muli", sans-serif;
  font-size: 16px;
  color: #2c2c2c;
}
body a {
  color: inherit;
  text-decoration: none;
}
.header__btn {
  transition-property: all;
  transition-duration: 0.2s;
  transition-timing-function: linear;
  transition-delay: 0s;
  padding: 10px 20px;
  display: inline-block;
  margin-right: 10px;
  background-color: #fff;
  border: 1px solid #2c2c2c;
  border-radius: 3px;
  cursor: pointer;
  outline: none;
}
.header__btn:last-child {
  margin-right: 0;
}
.header__btn:hover, .header__btn.js-active {
  color: #fff;
  background-color: #2c2c2c;
}
.header {
  max-width: 600px;
  margin: 50px auto;
  text-align: center;
}
.header__title {
  margin-bottom: 30px;
  font-size: 2.1rem;
}
.content {
  width: 95%;
  margin: 0 auto 50px;
}
.password-strength {
  box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.3);
}
.js-hidden {
  display: none;
}
</style>

</head>
<body>
<div class="content">
    <!--content inner-->
    <div class="content__inner">
        <div class="container">
            <div class="row">
                <div class="col-lg-6 m-auto">
                    <form class="password-strength form p-4">
                        <h3 class="form__title text-center mb-4">Enter the Password</h3>
                        <div class="form-group">
                            <label for="password-input">Password</label>
                            <div class="input-group">
                                <input class="password-strength__input form-control" type="password" id="password-input" aria-describedby="passwordHelp" placeholder="Enter password" />
                                <div class="input-group-append">
                                    <button class="password-strength__visibility btn btn-outline-secondary" type="button"><span class="password-strength__visibility-icon" data-visible="hidden"><i class="fas fa-eye-slash"></i></span><span class="password-strength__visibility-icon js-hidden" data-visible="visible"><i class="fas fa-eye"></i></span></button>
                                </div>
                            </div><small class="password-strength__error text-danger js-hidden">This symbol is not allowed!</small><small class="form-text text-muted mt-2" id="passwordHelp">Add 9 charachters or more, lowercase letters, uppercase letters, numbers and symbols to make the password really strong!</small>
                        </div>
                        <div class="password-strength__bar-block progress mb-4">
                            <div class="password-strength__bar progress-bar bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <button class="password-strength__submit btn btn-success d-flex m-auto" type="button" disabled="disabled">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div><div id="bcl"><a style="font-size:8pt;text-decoration:none;" href="http://www.devanswer.com">Free Frontend</a></div>
<script>
DOM = {
  passwForm: '.password-strength',
  passwErrorMsg: '.password-strength__error',
  passwInput: document.querySelector('.password-strength__input'),
  passwVisibilityBtn: '.password-strength__visibility',
  passwVisibility_icon: '.password-strength__visibility-icon',
  strengthBar: document.querySelector('.password-strength__bar'),
  submitBtn: document.querySelector('.password-strength__submit') };
//*** HELPERS
//need to append classname with '.' symbol
const findParentNode = (elem, parentClass) => {
  parentClass = parentClass.slice(1, parentClass.length);
  while (true) {

    if (!elem.classList.contains(parentClass)) {
      elem = elem.parentNode;
    } else {
      return elem;
    }
  }
};
//*** MAIN CODE
const getPasswordVal = input => {
  return input.value;
};
const testPasswRegexp = (passw, regexp) => {

  return regexp.test(passw);

};
const testPassw = passw => {
  let strength = 'none';
  const moderate = /(?=.*[A-Z])(?=.*[a-z]).{5,}|(?=.*[\d])(?=.*[a-z]).{5,}|(?=.*[\d])(?=.*[A-Z])(?=.*[a-z]).{5,}/g;
  const strong = /(?=.*[A-Z])(?=.*[a-z])(?=.*[\d]).{7,}|(?=.*[\!@#$%^&*()\\[\]{}\-_+=~`|:;"'<>,./?])(?=.*[a-z])(?=.*[\d]).{7,}/g;
  const extraStrong = /(?=.*[A-Z])(?=.*[a-z])(?=.*[\d])(?=.*[\!@#$%^&*()\\[\]{}\-_+=~`|:;"'<>,./?]).{9,}/g;
  if (testPasswRegexp(passw, extraStrong)) {
    strength = 'extra';
  } else if (testPasswRegexp(passw, strong)) {
    strength = 'strong';
  } else if (testPasswRegexp(passw, moderate)) {
    strength = 'moderate';
  } else if (passw.length > 0) {
    strength = 'weak';
  }
  return strength;
};
const testPasswError = passw => {
  const errorSymbols = /\s/g;
  return testPasswRegexp(passw, errorSymbols);
};
const setStrengthBarValue = (bar, strength) => {
  let strengthValue;
  switch (strength) {
    case 'weak':
      strengthValue = 25;
      bar.setAttribute('aria-valuenow', strengthValue);
      break;
    case 'moderate':
      strengthValue = 50;
      bar.setAttribute('aria-valuenow', strengthValue);
      break;
    case 'strong':
      strengthValue = 75;
      bar.setAttribute('aria-valuenow', strengthValue);
      break;
    case 'extra':
      strengthValue = 100;
      bar.setAttribute('aria-valuenow', strengthValue);
      break;
    default:
      strengthValue = 0;
      bar.setAttribute('aria-valuenow', 0);}
  return strengthValue;
};
//also adds a text label based on styles
const setStrengthBarStyles = (bar, strengthValue) => {
  bar.style.width = `${strengthValue}%`;
  bar.classList.remove('bg-success', 'bg-info', 'bg-warning');
  switch (strengthValue) {
    case 25:
      bar.classList.add('bg-danger');
      bar.textContent = 'Weak';
      break;
    case 50:
      bar.classList.remove('bg-danger');
      bar.classList.add('bg-warning');
      bar.textContent = 'Moderate';
      break;
    case 75:
      bar.classList.remove('bg-danger');
      bar.classList.add('bg-info');
      bar.textContent = 'Strong';
      break;
    case 100:
      bar.classList.remove('bg-danger');
      bar.classList.add('bg-success');
      bar.textContent = 'Extra Strong';
      break;
    default:
      bar.classList.add('bg-danger');
      bar.textContent = '';
      bar.style.width = `0`;}
};
const setStrengthBar = (bar, strength) => {
  //setting value
  const strengthValue = setStrengthBarValue(bar, strength);
  //setting styles
  setStrengthBarStyles(bar, strengthValue);
};
const unblockSubmitBtn = (btn, strength) => {
  if (strength === 'none' || strength === 'weak') {
    btn.disabled = true;
  } else {
    btn.disabled = false;
  }
};
const findErrorMsg = input => {
  const passwForm = findParentNode(input, DOM.passwForm);
  return passwForm.querySelector(DOM.passwErrorMsg);
};
const showErrorMsg = input => {
  const errorMsg = findErrorMsg(input);
  errorMsg.classList.remove('js-hidden');
};
const hideErrorMsg = input => {
  const errorMsg = findErrorMsg(input);
  errorMsg.classList.add('js-hidden');
};
const passwordStrength = (input, strengthBar, btn) => {
  //getting password
  const passw = getPasswordVal(input);
  //check if there is an error
  const error = testPasswError(passw);
  if (error) {
    showErrorMsg(input);
  } else {
    //hide error messages
    hideErrorMsg(input);
    //finding strength
    const strength = testPassw(passw);
    //setting strength bar (value and styles)
    setStrengthBar(strengthBar, strength);
    //unblock submit btn only if password is moderate or stronger
    unblockSubmitBtn(btn, strength);
  }
};
const passwordVisible = passwField => {
  const passwType = passwField.getAttribute('type');
  let visibilityStatus;
  if (passwType === 'text') {
    passwField.setAttribute('type', 'password');
    visibilityStatus = 'hidden';
  } else {
    passwField.setAttribute('type', 'text');
    visibilityStatus = 'visible';
  }
  return visibilityStatus;
};
const changeVisibiltyBtnIcon = (btn, status) => {
  const hiddenPasswIcon = btn.querySelector(`${DOM.passwVisibility_icon}[data-visible="hidden"]`);
  const visibilePasswIcon = btn.querySelector(`${DOM.passwVisibility_icon}[data-visible="visible"]`);
  if (status === 'visible') {
    visibilePasswIcon.classList.remove('js-hidden');
    hiddenPasswIcon.classList.add('js-hidden');
  } else if (status === 'hidden') {
    visibilePasswIcon.classList.add('js-hidden');
    hiddenPasswIcon.classList.remove('js-hidden');
  }
};
const passwVisibilitySwitcher = (passwField, visibilityToggler) => {
  const visibilityStatus = passwordVisible(passwField);
  changeVisibiltyBtnIcon(visibilityToggler, visibilityStatus);
};
//*** EVENT LISTENERS
DOM.passwInput.addEventListener('input', () => {
  passwordStrength(DOM.passwInput, DOM.strengthBar, DOM.submitBtn);
});
const passwVisibilityBtn = document.querySelector(DOM.passwVisibilityBtn);
passwVisibilityBtn.addEventListener('click', e => {
  let toggler = findParentNode(e.target, DOM.passwVisibilityBtn);
  passwVisibilitySwitcher(DOM.passwInput, toggler);
});
</script>

</body>
</html>
Preview