strong password checker javascript code example
Example 1: Javascript validate password
let pattern = new RegExp("^(?=(.*[a-zA-Z]){1,})(?=(.*[0-9]){2,}).{8,}$");
let inputToListen = document.getElementById('pass-one');
let valide = document.getElementsByClassName('indicator')[0];
inputToListen.addEventListener('input', function () {
if(pattern.test(inputToListen.value)){
valide.innerHTML = 'ok';
}else{
valide.innerHTML = 'not ok'
}
});
Example 2: password strength checker javascript
<script language="javascript">
function passwordChanged() {
var strength = document.getElementById('strength');
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>';
}
}
</script>
<input name="password" id="password" type="text" size="15" maxlength="100" onkeyup="return passwordChanged();" />
<span id="strength">Type Password</span>