How to implement a random password generator using JavaScript

Securing our online accounts is becoming increasingly important. An essential element of account security is maintaining strong and distinct passwords for each account. While the temptation is there to use simple passwords or reuse the same password for multiple accounts, such behavior can leave us open to cyber threats.

In this Answer, we'll explore how to create a random password generator using JavaScript. The program that we develop will generate secure passwords that are both difficult to guess and resistant to brute-force attacks. The output of our application will look like this.

Expected output
Expected output

Why use a random password generator?

Using a random password generator significantly enhances online security by creating strong, unique, and unpredictable passwords that are resistant to various forms of cyberattacks. Here are the main reasons why using a random password generator is crucial for online securityOnline security refers to the measures and practices implemented to protect computers, networks, programs, and data from unauthorized access, attacks, damage, or theft when using the internet.:

  1. Stronger passwords: Randomly generated passwords are often much stronger than manually established passwords. They often contain a combination of lowercase and uppercase letters, special characters, and numbers, making them more resistant to hackers.

  2. Unique passwords: Using unique passwords for each of our accounts ensures that if one account is compromised, our other accounts remain safe. A random password generator makes it easy to create unique passwords for every account we own.

  3. Ease of use: A well-designed password generator can streamline the process of creating secure passwords. With just a few clicks, we can generate a strong password that meets the requirements of many online services.

Now that we understand the importance of using a random password generator, let's discuss its implementation.

Implementing the random password generator

We'll build a simple random password generator using JavaScript. Our generator will allow users to specify the length of the password and whether they want to include uppercase letters, lowercase letters, numbers, and special characters.

HTML for random password generator

First, let's create the HTML structure for our password generator. We'll include input fields for specifying the password length and checkboxes for selecting character types.

HTML for random password generator
  • Lines 9–37: We define the user interface elements for the random password generator. It includes input fields for specifying password length and checkboxes for selecting character types. Users can customize their password preferences and generate a random password with the click of a button.

JavaScript for random password generator

Next, let's implement the JavaScript functionality to generate random passwords based on the user's input.

// Function to generate a random password
function generatePassword() {
const length = document.getElementById('password-length').value;
const uppercase = document.getElementById('include-uppercase').checked;
const lowercase = document.getElementById('include-lowercase').checked;
const numbers = document.getElementById('include-numbers').checked;
const specialCharacters = document.getElementById('include-special-characters').checked;
let characters = '';
if (uppercase) characters += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (lowercase) characters += 'abcdefghijklmnopqrstuvwxyz';
if (numbers) characters += '0123456789';
if (specialCharacters) characters += '!@#$%^&*()_+{}[]';
let password = '';
for (let i = 0; i < length; i++) {
password += characters.charAt(Math.floor(Math.random() * characters.length));
}
document.getElementById('password').value = password;
}
// Event listener for the "Generate Password" button
document.getElementById('generate-password').addEventListener('click', generatePassword);
  • Lines 2–21:We created a function to generate a random password that retrieves user input values and defines character sets based on user preferences.

  • Line 3: Retrieve the desired password length from an input field with the ID password-length.

  • Line 4: Check whether to include uppercase letters in the password from a checkbox with the ID include-uppercase.

  • Line 5: Check whether to include lowercase letters in the password from a checkbox with the ID include-lowercase.

  • Line 6: Check whether to include numbers in the password from a checkbox with the ID include-numbers.

  • Line 7: Check whether to include special characters in the password from a checkbox with the ID include-special-characters.

  • Line 9: Initialize an empty string to store the possible characters for the password.

  • Line 10: If uppercase letters are to be included, append them to the characters string.

  • Line 11: If lowercase letters are to be included, append them to the characters string.

  • Line 12: If numbers are to be included, append them to the characters string.

  • Lines 16–18: Loop for the length of the desired password, adding a random character from the characters string to password.

  • Line 24: We created an event listener for the "Generate Password" button.

Styling for random password generator

Finally, we can add some CSS to style the password generator and make it visually appealing.

/* styles.css */
body {
font-family: Arial, sans-serif;
}
.container {
max-width: 600px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
text-align: center;
}
.form-group {
margin-bottom: 15px;
}
input[type="number"] {
width: 60px;
text-align: center;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
textarea {
width: 100%;
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
resize: none;
}
  • Lines 3–5: This ensures that the text on the web page is displayed in a clean sans-serif font, which is generally easier to read on screens and gives the page a modern look.

  • Lines 7–14: We create a custom style for the container and create a visually appealing, centered container with defined spacing, a subtle border, and rounded corners, making the content within it easy to read and aesthetically pleasing.

  • Lines 16–18: This ensures that there is consistent spacing between each form group, making the form layout more visually appealing and easier to navigate.

  • Lines 34–41: This ensures that textarea contains 100% width with 1px border and 20px margin from top.

Demo application

Let's see the complete functional application:

Complete application

Conclusion

We learned how to create a random password generator using JavaScript. By following the step-by-step guide and implementing the provided code snippets, we can build a security tool to generate strong passwords for our online accounts. Remember to use unique passwords for each account, and consider using a password manager to store and manage them securely. By taking these precautions, we can enhance the security of our online presence and protect our sensitive information from unauthorized access.

Copyright ©2024 Educative, Inc. All rights reserved