Hello Developers,
In this demonstration, I will show you how to check password strength using JavaScript. Here I will use regular expressions.
First Step: Create the html password input field
Here we have to use some CSS code which is given below:
<style>
.passwordInput {
margin-top: 5%;
text-align: center;
}
.displayBadge {
margin-top: 1%;
display: none;
text-align: center;
color: white;
}
</style>
After that,
<div class="col-md-12 col-sm-12 form-group">
<input type="password" name="password" id="password" placeholder="Enter Password"
value="">
</div>
<span id="StrengthDisp" class="badge displayBadge col-md-12 col-sm-12">Weak</span>
<br>
we have to create the input field. The code is:
Second Step: Write the JavaScript Code
Here is the output:
For Securing the password we have created several conditions:
?=.*[a-z]
), one uppercase letter (?=.*[A-Z]
), one digit (?=.*[0-9]
), one special character (?=.*[^A-Za-z0-9]
), and is at least eight characters long(?=.{8,}
).|
to check for either of the two conditions (?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{6,})
or (?=.*[a-z])(?=.*[A-Z])(?=.*[^A-Za-z0-9])(?=.{8,})
.
The JavaScript code is:
<script>
let timeout;
let password = document.getElementById('password')
let strengthBadge = document.getElementById('StrengthDisp')
let strongPassword = new RegExp('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{8,})')
let mediumPassword = new RegExp(
'((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{6,}))|((?=.*[a-z])(?=.*[A-Z])(?=.*[^A-Za-z0-9])(?=.{8,}))'
)
function StrengthChecker(PasswordParameter) {
if (strongPassword.test(PasswordParameter)) {
strengthBadge.style.backgroundColor = "green"
strengthBadge.textContent = 'Strong'
} else if (mediumPassword.test(PasswordParameter)) {
strengthBadge.style.backgroundColor = 'blue'
strengthBadge.textContent = 'Medium'
} else {
strengthBadge.style.backgroundColor = 'red'
strengthBadge.textContent = 'Weak'
}
}
password.addEventListener("input", () => {
strengthBadge.style.display = 'block'
clearTimeout(timeout);
timeout = setTimeout(() => StrengthChecker(password.value), 500);
if (password.value.length !== 0) {
strengthBadge.style.display != 'block'
} else {
strengthBadge.style.display = 'none'
}
});
</script>
That's it for today. From the above part, you will learn how to use JavaScript RegEx to create a three-level password checker.
Hope you might get help with the journey of development.
Read More: Calculate years months days between two dates in JavaScript