Skip to content

Instantly share code, notes, and snippets.

@be-mohand
Created April 20, 2021 15:30
Show Gist options
  • Save be-mohand/c74c5b9dc846be996112e21154f2a40c to your computer and use it in GitHub Desktop.
Save be-mohand/c74c5b9dc846be996112e21154f2a40c to your computer and use it in GitHub Desktop.
Check password strength in javascript
/**
* Thank You Douglas Karr for this javascript function
* @link https://martech.zone/javascript-password-strength/
*/
if($('#signupForm').length > 0 && $('#password').length > 0) {
$('#password-input-div').append('<span id="passwordStrength"></span>');
$('#password').on('keyup', function(){
var strength = document.getElementById("passwordStrength");
var strongRegex = new RegExp("^(?=.{14,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{10,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{8,}).*", "g");
var pwd = document.getElementById("password");
if (pwd.value.length === 0) {
strength.innerHTML = 'Type Password';
} else if (false === enoughRegex.test(pwd.value)) {
strength.innerHTML = 'More Characters';
} else if (strongRegex.test(pwd.value)) {
strength.innerHTML = '<span style="color:green">Strong!</span>';
} else if (mediumRegex.test(pwd.value)) {
strength.innerHTML = '<span style="color:orange">Medium!</span>';
} else {
strength.innerHTML = '<span style="color:red">Weak!</span>';
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment