How to check the strength of a password with javascript
Updated: 17-Oct-2022 / Tags: HTML, CSS and Javascript / Views: 1274 - Author: George
Introduction
Hello everyone, in this tutorial we are going to check a password's strength with javascript, by creating a password strength checker. A good, and in a way secure password must contain lowercase letters, uppercase letters, numbers, and special characters, and must be at least seven characters long.
So we are going to write some JavaScript code to check a password on how many of those character types contains, and measure it's strength.
Live example
Check the live example below, but let me explain first how the code works.
- If you enter a white space the application will return an error.
- If you enter < > characters the application will return an error.
- If the password is greater than 12 characters long, the code will return an error.
- To see how the strength-bar works, try out some combinations, first enter lowercase letters, then add some numbers, then uppercase letters, and last special characters.
Now that you have tried out the live demo, you will have a better understanding
on what we are going to code.
So let's see what files we need.
Project's folder
We need three files to make this application to work.
- We need an index.php file in which we will write the html code.
- We need a script.js file in which we are going to write the javascript code.
-
And last we need a styles.css file to write the css. I will not go through the whole css code but
i will mention the important stuff that we use in combination with the JavaScript code.
If you download the source code you will get the whole project including the css code.
The index.php file
In the index file we have our form with the password field, and the popup element with the strength-bar and the description text.
<form action="" method="post">
<div class="password-container">
<label>Enter Password</label>
<input type="text" name="password" id="password-field" >
<div class="strength-container">
<p class="title">
Password strength:
<span class="strength-text"></span>
</p>
<div class="strength-bar-wrapper">
<div id="strength-bar"></div>
</div>
<p class="strength-description">
Passwords should be at least <i>7</i>
characters long and max <i>12</i>. <br>
Try use <strong>lowercasing</strong> and <strong>uppercasing</strong>,
<strong>numbers</strong> and <strong>symbols</strong>.
</p>
<div class="arrow"></div>
</div>
</div>
<button type="submit">Submit</button>
</form>
<script src="script.js"></script>
HTML code breakdown
Let's break down the form element
-
In the first line we have the form element. We have the action attribute which we have set to an empty string. And we have the method attribute with the value set to post.
<form action="" method="post">
- action="" ... this means that the form will submit the data to the same page
- method="post" ... the post http method will send the data to the server with the POST method.
- Although we don't need those attributes in this tutorial, it's a good practice to include them in case you want to expand the form and add more fields and send the data to the server. Which you probably will.
-
Inside the form and in line 3 we have the "password-container", inside this element we have the password and the popup element. If you want to add more input fields in the form put them above or under the "password-container".
<div class="password-container">
-
Inside the password-container we have in line 4 the label, and in line 5 the input element.
<label>Enter Password</label> <input type="text" name="password" id="password-field" >
The input field has a name of "password" and an id of "password-field". We are going to use the id to target the element in the javascript file.
-
Next in line 7 we have the "strength-container" element. This is the element that will popup next to the password and will display the strength-bar and the description.
<div class="strength-container">
The "strength-container" is by default hidden by setting the display property to "none" in the css code. We will target in the javascript file the element using the element's class, and set the display property to "block" when we click on the password field.
-
The first element that we have inside the "strength-container" is the "title" element.
<p class="title"> Password strength: <span class="strength-text"> <!-- Displays the strength text with javascript, Short, Weak, etc --> </span> </p>
Inside the "title" element we have a span element with a class of "strength-text". Again we are going to use javascript to display the strength text in the elements body.
-
Next in line 14 we have the "strength-bar" inside the "strength-bar-wrapper".
<div class="strength-bar-wrapper"> <div id="strength-bar"></div> </div>
The width of the "strength-bar" is set to zero in the css code. We will manipulate the width from the javascript file accordingly the strength of the password.
-
In line 16 we have the information that the user need to insert a strong password.
<p class="strength-description"> Passwords should be at least <i>7</i> characters long and max <i>12</i>. <br> Try use <strong>lowercasing</strong> and <strong>uppercasing</strong>, <strong>numbers</strong> and <strong>symbols</strong>. </p>
-
In line 22 we have a div element with a class of "arrow". We are going to manipulate this element to look like an arrow in the css code. In line 23 we are closing the "strength-container", and in line 24 we closing the "password-container".
<div class="arrow"></div> </div> <!-- End of the "strength-container" --> </div> <!-- End of the "password-container" -->
-
In line 26 we have the submit button, which is irrelevant for this tutorial, but as i said you are going to need it if you want to add more fields and make this form functional.
And in line 27 we are closing the form. And this is all the html that we need.<button type="submit">Submit</button> </form>
-
And in line 29 we have the script tag which points to the "script.js" file so we can run the javascript code in the index.php file.
<script src="script.js"></script>
And we are done with the index file. Now let's go to the script.js file and write the javascript code.
The Javascript file
Starting to code in the javascript file we are going to set first some global variables that we will use in the entire script.
let password = document.querySelector("#password-field");
let strengthContainer = document.querySelector(".strength-container");
let strengthBar = document.querySelector("#strength-bar");
let strengthText = document.querySelector(".strength-text");
- In the first line we are targeting the password input field and store the element in the password variable.
- In line 2 we are targeting the "strength-container", and store the element in the strengthContainer variable.
- In line 3 we are targeting the "strength-bar", and store the element in the strengthBar variable.
- And in line 4 we are targeting the "strength-text" span element, and store it in the strengthText variable.
Next we are going to add an event-listener on the password field targeting the "focus" event.
This means that when we click inside the password input field a function will run.
password.addEventListener("focus", function(){
strengthContainer.style.display = "block";
});
Inside the function in line 7, we are setting the display property of the "strength-container" to "block".
This means that we are going to make the element visible, whenever we click inside the password field.
Remember that the "strength-container" is hidden by default.
Next we are going to set another event-listener on the password field, but this time we are targeting the "blur" event. This means that when we are clicking anywhere outside the password field a function will run.
password.addEventListener("blur", function(){
strengthContainer.style.display = "none";
});
Inside the function we will set the display property back to "none", so we hide the "strength-container" element.
Next we are going to have a function named setStrength() which is setting the width of the "strength-bar".
The function takes as an argument the value that we set accordingly to the calculated strength.
function setStrength(value){
strengthBar.style.width = value + "%";
}
The value that the argument (value) holds is turned in a percentage number.
Next we are going to have a function named setColorAndText(). The function takes two arguments, in the first argument we set the color of the "strength-bar" and the text, and in the second argument we are inserting the text that we will display. In example: setColorAndText("red", "Short")
function setColorAndText(color, text){
strengthBar.style.backgroundColor = color;
strengthText.innerHTML = text;
strengthText.style.color = color;
}
Next we are going to have a function named clearStrength(). This function will clear the "strength-bar" when we press the backspace and there are no characters left in the password field.
function clearStrength(){
strengthBar.style.width = 0;
strengthBar.style.backgroundColor = "";
strengthText.innerHTML = "";
}
-
In line 25 we set the width of the "strength-bar" back to zero, this is the default width
that is set in the css file.
- In line 26 we remove any background color.
- And in line 27 we clear the "strength-text".
Next we are gonna add an event-listener on the "password-field". We are going to target the "keyup" event, this means that every time we press and release a key on the keyboard the checkPasswordStrength function will run.
password.addEventListener("keyup", checkPasswordStrength);
Now we are going to write the checkPasswordStrength() function to calculate the password's strength.
function checkPasswordStrength(){
}
The first thing that we do inside the function is to create a variable named strength and set its value to zero. Accordingly to the password's strength we are going to set different values to the strength variable.
let strength = 0;
Next we are going to check the password's value and if it is empty we will run the clearStrength() function and return false stopping the function here.
if(password.value == ""){
clearStrength();
return false;
}
Next we are going to check the password for any white space. If this is true we are going to run the setColorAndText() function and set the color to "red" and the text message to "White space is not allowed" and return false to stop the function here.
if(password.value.match(/\s/)){
setColorAndText("red", "White space is not allowed");
return false;
}
Next we are going to check the password for any less than (<) or greater than (>) characters. If this is true we are going to run the setColorAndText() function and set the color to "red" and the text message to "< > characters are not allowed". And again we will stop the function from further execution by returning false.
if(password.value.match(/<|>/)){
setColorAndText("red", "< > characters are not allowed");
return false;
}
Next we are going to check if the password is greater than 12 characters. If this is the case we are going to set the color to "red", and the text-message to "Password greater than 12 char". And return false;
if(password.value.length > 12){
setColorAndText("red", "Password greater than 12 char.");
return false;
}
Next we are going to have an if else statement. If the password is less than 7 characters we are going to set the strength to 20, the color to "red", and the text-message to "Too short". We want the password's length to be between 7 and 12 characters long.
if(password.value.length < 7){
strength = 20;
setColorAndText("red", "Too short"); // short
}else{
Next, and inside the else clause, we are going to run the match method against the password and we will check for the four character types that we want the password to contain. The match method returns an array of the matched characters, or null if there is no match.
let lowerCase = password.value.match(/[a-z]/);
let upperCase = password.value.match(/[A-Z]/);
let numbers = password.value.match(/[0-9]/);
let specialCharacters = password.value.match(/[\!\~\@\&\#\$\%\^\&\*\(\)\{\}\?\-\_\+\=]/);
- In line 52 we search for lowercase letters [/[a-z]/], and store the result in the lowerCase variable.
- In line 53 we search for uppercase letters /[A-Z]/, and we store the result in the upperCase variable.
- In line 54 we search for numbers /[0-9]/, and we store the result in the numbers variable.
- And in line 55 we search for special characters /[\!\~\@\&\#\$\%\^\&\*\(\)\{\}\?\-\_\+\=]/, and we store the result in the specialCharacters variable.
Now it's time to calculate the password's strength.
We are going to start by defining a weak password. A weak password contains only one of the four character
types. If this is the case we are going to set the strength to 40, the color to "red" and the text-message to "Weak".
if(lowerCase || upperCase || numbers || specialCharacters){
strength = 40;
setColorAndText("red", "Weak");
}
Next we are going to define a medium password.
A medium password contains only two of the four character types. The if condition checks every
possible combination that consists of two character types. In example lowerCase and upperCase, or upperCase and specialCharacters,
and so on.
if(
(lowerCase && upperCase) || (lowerCase && numbers) || (lowerCase && specialCharacters) ||
(upperCase && numbers) || (upperCase && specialCharacters) || (numbers && specialCharacters)
)
{
strength = 60;
setColorAndText("orange", "Medium");
}
If the password has only two of the four character types, we set the strength to 60, the color to "orange" and the text-message to "Medium".
Next we are going to define a strong password.
A strong password contains three of the four character types.
Again we check every possible combination that contains three of the four character types. If this is the case we set the
strength to 80, the color to light green "088f08", and the text-message to "Strong".
if( (lowerCase && upperCase && numbers) || (lowerCase && upperCase && specialCharacters) ||
(lowerCase && numbers && specialCharacters) || (upperCase && numbers && specialCharacters)
)
{
strength = 80;
setColorAndText("#088f08", "Strong");
}
And last we have a very strong password if all four character types are present in the password.
If this is the case, we set the strength to 100, the color to "green" and the text-message to "Very Strong".
if(lowerCase && upperCase && numbers && specialCharacters){
strength = 100;
setColorAndText("green", "Very Strong");
}
And to complete the function and this tutorial, we close the parent if statement in line 83,
and we call the setStrength() function and pass in the strength variable as an argument.
And very last we close the checkPasswordStrength() function in line 85.
}
setStrength(strength);
}
Summary
And that's it. We completed the whole code on how to check the strength of a password with javascript.
Last Words
Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any error's, so i can update the page with the correct code.
Source code
You can download the source code and use it in any way you like.
Times downloaded: 270
Comment section
You can leave a comment, it will help me a lot.
Or you can just say hi. 😉