Random Password Generator JavaScript


In this tutorial, we are going to create a javascript password generator app. This app is going to be customizable and can be used to create any kind of password.

The app will have the following features:

The password created using this app is going to be a very strong password, since it includes all keyword combinations like numbers, symbols, uppercase, and lowercase alphabets and the password is sufficiently long. The password is going to be random and unique so that it is not easy to guess.

Here is a preview of the app:

password generator app in javascript Test the app

Why do we need a strong password?

Password is the first defense against unauthorized access to your accounts or devices, so you need a stronger password to prevent attacks from hackers.

Simple and small passwords with just uppercase or lowercase letters are pretty easy to crack. Passwords with a good combination of numbers, symbols, uppercase, and lowercase letters are very tough to crack.

The more complex the password is more secure and strong it is.


How to make a JavaScript password generator?

We are going to use HTML to create the structure of the app, CSS to design and style the app, and JavaScript to create logic and other feature of the app.

To create a Javascript password generator we will go through 3 steps:

  1. Creating app structure with HTML
  2. Styling with CSS
  3. Creating logic with javascript

1. Creating app structure with HTML

The first step is to create the HTML structure of the app. The HTML structure is going to be like this:

  1. A box to show the generated password and a copy button to copy the password.
  2. A number input box for taking input for the length of the password.
  3. 4 checkboxes for taking input whether to include number, symbol, uppercase, and lowercase in password or not
  4. A button to generate the password
Javascript password generator structure
Javascript password generator structure

After creating these items we will wrap these items in the <div> element and then add classes to it for styling purposes.

Ⅰ. Creating a box to show password

first create a <p> tag to show the password and add 'passwordBox' id to it for later access, also create a copy icon button using the font-awesome icon.

Now wrap these 2 item in a single <div> element with CSS class of 'password'. We will use this class later to style the elements.

<div class="password">
  <p id="passwordBox"></p>
  <i class="far fa-clipboard" onclick="copyPassword()"></i>
</div>

Ⅱ. Creating an input box for taking password length as input.

Now create an input box for the length of the password using <input> tag, with type number. Create a label for it and provide min, max, and value attribute to it.

Add 'length' as an id to <input> tag and wrap both <label> tag and <input> tag in <div> element so that we may align is side by side.

<div>
  <label for="length">Length</label>
  <input type="number" id="length" min="6" max="20" value="6">
</div>

Ⅲ. Creating a checkbox for selecting the type of characters in the password

We will now create 4 checkboxes for number, symbol, lowerCase, and upperCase respectively for selecting the type of characters to add in the password and wrap each of these inputs in an <input> element.

Again we will wrap each pair within an <div> element to align it side by side.

<div>
  <label for="symbol">Include Symbol</label>
  <input type="checkbox" id="symbol" checked>
</div>
<div>
  <label for="number">Include Number</label>
  <input type="checkbox" id="number" checked>
</div>
<div>
  <label for="lowerCase">Include lowerCase</label>
  <input type="checkbox" id="lowerCase" checked>
</div>
<div>
  <label for="upperCase">Include upperCase</label>
  <input type="checkbox" id="upperCase" checked>
</div>

Ⅳ. Creating a password generator button.

Now create a button and add onclick event to it with "createPassword()" function.

<button onclick="createPassword()">Get Random Password</button>

Add font-awesome CDN in the head for the icon. Here is the complete HTML code password generator.

Here is the complete HTML code for the app.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Random Password Generator In Javascript</title>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css'>
</head>

<body>
  <div class="container">
    <div class="password-generator">
      <h2>Password Generator</h2>
      <div class="password">
        <p id="passwordBox"></p><i class="far fa-clipboard" onclick="copyPassword()"></i></i>
      </div>
      <div>
        <label for="length">Length</label>
        <input type="number" id="length" min="6" max="20" value="6">
      </div>
      <div>
        <label for="symbol">Include Symbol</label>
        <input type="checkbox" id="symbol" checked>
      </div>
      <div>
        <label for="number">Include Number</label>
        <input type="checkbox" id="number" checked>
      </div>
      <div>
        <label for="lowerCase">Include lowerCase</label>
        <input type="checkbox" id="lowerCase" checked>
      </div>
      <div>
        <label for="upperCase">Include upperCase</label>
        <input type="checkbox" id="upperCase" checked>
      </div>
      <button onclick="createPassword()">Get Random Password</button>
    </div>
  </div>
</body>

</html>

This is the output of the HTML code.

HTML output for random password generator
HTML output of password generator

2. Styling CSS

Now use CSS to style the app to look beautiful. We are using CSS flexbox properties to align-items.

Align the app to the center of the window screen using flexbox. Apply "display: flex;align-items: center;justify-content: center" on '.container' class to align app vertically and horizontally in center of the screen.

Now apply the justify-content property to the div elements that we used to wrap the pairs of labels and inputs to align at both ends of the element. i.e

.password-generator div {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}

Finally, add other basic CSS styles to the classes we achieve the final look. Look at the full CSS code below. Adding this code to the app will create the final look of the app.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #9b415c;
  height: 100vh;
}

.password-generator {
  padding: 40px;
  background-color: #6f2f42;
  color: white;
  font-size: 20px;
  font-family: sans-serif;
}

.password-generator div {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}

.password {
  min-width: 280px;
  background-color: #431c27;
  color: rgb(199, 199, 199);
}

.password p {
  padding: 6px 10px;
}

.password i {
  background-color: rgba(0, 0, 0, 0.575);
  padding: 6px 10px;
}

.password-generator button {
  width: 100%;
  border: none;
  color: rgba(255, 255, 255, 0.699);
  background-color: #2c131a;
  padding: 10px;
}

3. Creating logic with javascript

Now it's time to create logic for the password generator. To proceed further we first must know, how to create a random number in javascript?. We will use random numbers to randomly select a character from a list of characters.

To create a random number use the Math.random() method. It returns a number between 0 and 1. We will use this concept to randomly select a character type and a character from that character type.

Defining different types of character strings

Let's create 4 strings that contain different types of characters numbers, symbols, upperCase and lowerCase letters to use further in the code.

Wrap these strings in an object named keys.

const keys = {
  upperCase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  lowerCase: "abcdefghijklmnopqrstuvwxyz",
  number: "0123456789",
  symbol: "!@#$%^&*()_+~\\`|}{[]:;?><,./-="
}

Creating a function that returns 1 random character from these strings

Now we will create a function for each of the above strings that returns a random character from the string, we will use these characters in the password.

The function generates a random number from 0 to the length of string - 1 and then returns the character at that index value of the random number from the specified string.

Math.floor(Math.random() * string.length) create a random number between 0 to length of string - 1.

Now create an array and put all these functions in the array as array members. Look at the code below.

const getKey = [
  function upperCase() {
    return keys.upperCase[Math.floor(Math.random() * keys.upperCase.length)];
  },
  function lowerCase() {
    return keys.lowerCase[Math.floor(Math.random() * keys.lowerCase.length)];
  },
  function number() {
    return keys.number[Math.floor(Math.random() * keys.number.length)];
  },
  function symbol() {
    return keys.symbol[Math.floor(Math.random() * keys.symbol.length)];
  }
];

We put all these functions in an array because we will further create a random number between 0 and the length of the array to get a random function.

This means we will randomly pick a function that will randomly pick a character from their specified string.

Creating a random password generator function

Let's now create a password generator function. First, check if at least one checkbox is checked for the function to proceed. If none of the checkboxes is checked then return the function.

To check if at least one checkbox is checked grab all checkboxes using document.getElementById access method, and check if it is checked using the checked property. It returns a boolean value.

Add all these boolean values and if it is 0 then all checkbox is unchecked.

const upper = document.getElementById("upperCase").checked;
const lower = document.getElementById("lowerCase").checked;
const number = document.getElementById("number").checked;
const symbol = document.getElementById("symbol").checked;
if (upper + lower + number + symbol === 0) {
  alert("Please check atleast one box!");
  return;
}

Now create an empty string named 'password' and run a while loop until the length of the 'password' string becomes equal to the length of the input password.

In each iteration of this loop create a random number between 0 and the length of the function array (0-4). Now check if the checkbox with the same name as the function is checked if it is checked then run the function and add the returned character to our password.

This loop will run until the password length becomes equal to the desired length of the password. And finally set the password as innerHTML of the password box.

Here is complete code of 'createPassword()' function.

function createPassword() {
  const upper = document.getElementById("upperCase").checked;
  const lower = document.getElementById("lowerCase").checked;
  const number = document.getElementById("number").checked;
  const symbol = document.getElementById("symbol").checked;
  if (upper + lower + number + symbol === 0) {
    alert("Please check atleast one box!");
    return;
  }
  const passwordBox = document.getElementById("passwordBox");
  const length = document.getElementById("length");
  let password = "";
  while (length.value > password.length) {
    let keyToAdd = getKey[Math.floor(Math.random() * getKey.length)];
    let isChecked = document.getElementById(keyToAdd.name).checked;
    if (isChecked) {
      password += keyToAdd();
    }
  }
  passwordBox.innerHTML = password;
}

The above function basically first selects a random function from the array 'getKey' and then runs it which then returns a random character from the string of that function. So there are 2 random selections making passwords more random.

Create a function to copy the code

This is the code to create a copy code functionality. It will copy the code to the clipboard of the device.

function copyPassword() {
  const textarea = document.createElement('textarea');
  const password = document.getElementById("passwordBox").innerText;
  if (!password) { return; }
  textarea.value = password;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  textarea.remove();
  alert('Password copied to clipboard');
}

Code for password generator javascript

const keys = {
  upperCase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  lowerCase: "abcdefghijklmnopqrstuvwxyz",
  number: "0123456789",
  symbol: "@#$%^&*()_+~|}{[]></-="
}
const getKey = [
  function upperCase() {
    return keys.upperCase[Math.floor(Math.random() * keys.upperCase.length)];
  },
  function lowerCase() {
    return keys.lowerCase[Math.floor(Math.random() * keys.lowerCase.length)];
  },
  function number() {
    return keys.number[Math.floor(Math.random() * keys.number.length)];
  },
  function symbol() {
    return keys.symbol[Math.floor(Math.random() * keys.symbol.length)];
  }
];

function createPassword() {
  const upper = document.getElementById("upperCase").checked;
  const lower = document.getElementById("lowerCase").checked;
  const number = document.getElementById("number").checked;
  const symbol = document.getElementById("symbol").checked;
  if (upper + lower + number + symbol === 0) {
    alert("Please check atleast one box!");
    return;
  }
  const passwordBox = document.getElementById("passwordBox");
  const length = document.getElementById("length");
  let password = "";
  while (length.value > password.length) {
    let keyToAdd = getKey[Math.floor(Math.random() * getKey.length)];
    let isChecked = document.getElementById(keyToAdd.name).checked;
    if (isChecked) {
      password += keyToAdd();
    }
  }
  passwordBox.innerHTML = password;
}
function copyPassword() {
  const textarea = document.createElement('textarea');
  const password = document.getElementById("passwordBox").innerText;
  if (!password) { return; }
  textarea.value = password;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  textarea.remove();
  alert('Password copied to clipboard');
}

Conclusion

We created a random password generator javascript app in this tutorial which is customizable. It creates a strong password with variable length and the ability to select the type of characters in the password.