Rabikant

Posted on March 9th

How to Create a Custom Password Generator

"Let's Learn How to Create a Custom Password Generator"

It is important to note that passwords are very important in the present world, where virtually everything is digitalized. However, the creation of suitable, complex and, more importantly, secure passwords with a combination of uppercase letters, lowercase letters, numbers, and symbols is often a tiresome process. Well, it is easier said than done; however, you can follow live lessons and create your password generator using HTML, CSS, and JavaScript! From here, we take you through the construction of a complete, fully-variable password generator, including general notes/examples for building your own.

Why Create a Password Generator?

Strong passwords that nobody can decipher or guess along with an excellent password cracking system is a must. Password generators assist by coming up with unique alphabetic and numerical passwords with both small and capital letters as well as symbols. By building a password generator, you gain:

Control on the parameters of password. Incredibility in terms of work flexibility that can allow for variation of characters’ numbers as well as sorts of characters. Advantages of deriving robust passwords at the click of a button at any given time.

Writing the code for the password generator

This project will also help refresh your skills, specifically JavaScript, CSS, and HTML.  

 <div class="page">
        <div class="head-cont">
            <h1>Password Generator</h1>
        </div>

        <!-- Password display field with Copy button -->
        <div class="result-container">
            <input type="text" readonly id="passwordField" class="result" placeholder="Your password will appear here">
            <button class="copy-btn" onclick="copyPassword()">Copy</button>
        </div>

        <!-- Password length control -->
        <div class="range-cont">
            <p class="password-length">Password Length</p>
            <input type="text" id="lengthDisplay" readonly value="12">
            <input type="range" value="12" id="length" min="8" max="20" oninput="updateLengthDisplay()">
        </div>

        <!-- Options for password generation -->
        <div class="option-cont">
            <label><input type="checkbox" id="uppercase" checked> Uppercase</label>
            <label><input type="checkbox" id="lowercase" checked> Lowercase</label>
            <label><input type="checkbox" id="numbers" checked> Numbers</label>
            <label><input type="checkbox" id="symbols"> Symbols</label>
            <label><input type="checkbox" id="avoidAmbiguous"> Avoid Ambiguous</label>
        </div>

        <!-- Generate button -->
        <div class="btn-cont">
            <button onclick="generatePassword()" class="btn">Generate Password</button>
        </div>
    </div>

Here's a breakdown of each part of the HTML structure for the password generator:

1. Main Container

The last but still the most external tag with the class «page» creates the main framework of the password generator interface. This

has padding, and white background, border-radius that makes the corners rounded so that the tool can look professional, and it aligned middle so that the tool may look neat.

2. Main Area

Inside the main container, we start with a header section:

 <div class="head-cont">
        <h1>Password Generator</h1>
 </div>

This section displays the title of the application. The

tag gives prominence to the title "Password Generator" and helps users immediately understand the purpose of the tool.

3. Password Display Field with Copy Button

The next section allows users to view the generated password and copy it with a single click:

        <div class="result-container">
            <input type="text" readonly id="passwordField" class="result" placeholder="Your password will appear here">
            <button class="copy-btn" onclick="copyPassword()">Copy</button>
        </div>
  • Password Field (): This text input is where the generated password will be shown as seen in the screenshot below:- read-only attribute: it does not allow user to unintentionally edit password right on there. The asterisk underscores inform the users of the location where the password shall appear.
  • Copy Button: This button also has an HTML attribute onclick with the value of copyPassword() this is a JavaScript function that copies the passwords to the clipboard. It enables the users to copy the password without need to select it by the use of the mouse and the keyboard.

4. Password Length Control

This section lets users specify the length of the password:

   <div class="range-cont">
      <p class="password-length">Password Length</p>
      <input type="text" id="lengthDisplay" readonly value="12">
      <input type="range" value="12" id="length" min="8" max="20" oninput="updateLengthDisplay()">
   </div>
  • Label : That is why the label “Password Length” means that the options below it refer to setting the desired number of characters of the generated password.
  • Length Display (): This input box displays the current length chosen by the user and with the help of rollover attribute is set to readonly, which means it will change its value using range slider.
  • Range Slider (): This slider allows users to choose the number of characters in the password ranging from 8 and 20. The oninput=“updateLengthDisplay()” activates a JavaScript function which updates the displayed length as the user moves the slider.

5. Password Generation Options

Here, checkboxes let users choose which character types to include in the password:

    <div class="option-cont">
            <label><input type="checkbox" id="uppercase" checked> Uppercase</label>
            <label><input type="checkbox" id="lowercase" checked> Lowercase</label>
            <label><input type="checkbox" id="numbers" checked> Numbers</label>
            <label><input type="checkbox" id="symbols"> Symbols</label>
            <label><input type="checkbox" id="avoidAmbiguous"> Avoid Ambiguous</label>
        </div>
  • Checkboxes for Character Types:
    • Uppercase, Lowercase, Numbers, Symbols: With the help of these checkboxes if ticked, password includes uppercase letters, lowercase letters, numbers, and symbols, respectively. …while the checked attribute makes uppercase, lowercase and numbers selection default.
    • Avoid Ambiguous Characters: This, when checked, removes potentially confusing characters from the password which is ‘ 0’, ‘O’, ‘1’, ‘l’.

It is user friendly since each is used to contain both the text description as well as the checkbox input element.

6. Create Button

This button triggers the password generation process:

   <div class="btn-cont">
            <button onclick="generatePassword()" class="btn">Generate Password</button>
        </div>
  • Generate Password Button: The onclick attribute calls the JavaScript function generatePassword() to create a new password based on the selected options. Styling and animation effects (such as background color changes) provide a more interactive experience for users.
 function generatePassword() {
            const length = document.getElementById('length').value;
            const includeUppercase = document.getElementById('uppercase').checked;
            const includeLowercase = document.getElementById('lowercase').checked;
            const includeNumbers = document.getElementById('numbers').checked;
            const includeSymbols = document.getElementById('symbols').checked;
            const avoidAmbiguous = document.getElementById('avoidAmbiguous').checked;

            // Character sets
            let uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            let lowercase = 'abcdefghijklmnopqrstuvwxyz';
            let numbers = '0123456789';
            let symbols = '!@#$%^&*()_+[]{}|;:,.<>?';
            let ambiguous = 'O0Il1';

            // Remove ambiguous characters if option is selected
            if (avoidAmbiguous) {
                uppercase = uppercase.replace(/[O]/g, '');
                lowercase = lowercase.replace(/[l]/g, '');
                numbers = numbers.replace(/[01]/g, '');
            }

            let charSet = '';
            if (includeUppercase) charSet += uppercase;
            if (includeLowercase) charSet += lowercase;
            if (includeNumbers) charSet += numbers;
            if (includeSymbols) charSet += symbols;

            if (charSet === '') {
                alert('Please select at least one option.');
                return;
            }

            let password = '';
            for (let i = 0; i < length; i++) {
                password += charSet.charAt(Math.floor(Math.random() * charSet.length));
            }

            // Display generated password in the text input field
            document.getElementById('passwordField').value = password;
        }

        function updateLengthDisplay() {
            const rangeValue = document.getElementById('length').value;
            document.getElementById('lengthDisplay').value = rangeValue;
        }

        function copyPassword() {
            const passwordField = document.getElementById('passwordField');
            passwordField.select();
            passwordField.setSelectionRange(0, 99999); // For mobile devices
            document.execCommand("copy");

            alert("Password copied to clipboard!");
        }

        // Initialize the display
        generatePassword();
        updateLengthDisplay();

Here's a breakdown of each part of the JavaScript code for the password generator:

1. generatePassword Function

This function is responsible for creating a random password based on the user’s selected options.

        function generatePassword() {
            const length = document.getElementById('length').value;
            const includeUppercase = document.getElementById('uppercase').checked;
            const includeLowercase = document.getElementById('lowercase').checked;
            const includeNumbers = document.getElementById('numbers').checked;
            const includeSymbols = document.getElementById('symbols').checked;
            const avoidAmbiguous = document.getElementById('avoidAmbiguous').checked;
  • Get User Selections: It begins by storing the selected password length of the password and the character options (uppercase, lower case letters, numbers, special characters and ambiguous characters) by using the document.getElementById and .value method.
  • Store User Options in Variables: To ensure readability, each of the options is stored in a variable needed for password generation.

2. Define Character Sets

            let uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            let lowercase = 'abcdefghijklmnopqrstuvwxyz';
            let numbers = '0123456789';
            let symbols = '!@#$%^&*()_+[]{}|;:,.<>?';
            let ambiguous = 'O0Il1';

This part defines the possible characters for each option:

  • Uppercase: A string containing all uppercase English letters.
  • Lowercase: A string containing all lowercase English letters.
  • Numbers: A string of digits 0-9.
  • Symbols: A string of common special characters.
  • Ambiguous Characters: Characters that might be confusing due to visual similarity (e.g., O vs. 0).

3. Remove Ambiguous Characters (if Selected)

            if (avoidAmbiguous) {
                uppercase = uppercase.replace(/[O]/g, '');
                lowercase = lowercase.replace(/[l]/g, '');
                numbers = numbers.replace(/[01]/g, '');
            }

If the user selects the Avoid Ambiguous option, this section removes certain characters (O, 0, l, and 1) from the respective strings. This makes the password easier to read and avoids potential confusion.

4. Build the Character Set Based on User Selection

      let charSet = '';
            if (includeUppercase) charSet += uppercase;
            if (includeLowercase) charSet += lowercase;
            if (includeNumbers) charSet += numbers;
            if (includeSymbols) charSet += symbols;
  • Create charSet: An empty string (charSet) is defined to store the final collection of characters that can be used in the password.
  • Add Selected Character Types: Based on the user’s selections, each category (uppercase, lowercase, numbers, symbols) is added to charSet. This ensures the generated password includes only the types the user has opted for.

5. Validate Character Set Selection

           if (charSet === '') {
                alert('Please select at least one option.');
                return;
            }

If no character type is selected (i.e., charSet is still empty), the function shows an alert to prompt the user to select at least one option and then exits early to avoid an empty password.

6. Generate the Password

            let password = '';
            for (let i = 0; i < length; i++) {
                password += charSet.charAt(Math.floor(Math.random() * charSet.length));
            }
  • Initialize Password Variable: A variable password is created to store the final result.
  • Build Password by Random Selection: Using a for loop, it iterates up to the selected password length. In each iteration, it randomly selects a character from charSet using Math.random() and appends it to the password string.

7. Display the Generated Password

            document.getElementById('passwordField').value = password;

This line sets the generated password as the value of the passwordField input, displaying it to the user.

8. updateLengthDisplay Function

        function updateLengthDisplay() {
            const rangeValue = document.getElementById('length').value;
            document.getElementById('lengthDisplay').value = rangeValue;
        }

This function is called whenever the user adjusts the password length slider. It updates the displayed length value in lengthDisplay to match the slider's current value.

9. copyPassword Function

        function copyPassword() {
            const passwordField = document.getElementById('passwordField');
            passwordField.select();
            passwordField.setSelectionRange(0, 99999); // For mobile devices
            document.execCommand("copy");

            alert("Password copied to clipboard!");
        }

This function enables users to copy the generated password with one click.

  • Select the Password Text: passwordField.select() highlights the password text in the passwordField input.
  • Copy to Clipboard: document.execCommand("copy") copies the selected text to the clipboard.
  • Confirmation Alert: Displays an alert confirming the password has been copied.

10. Initialize the Display

      generatePassword();
      updateLengthDisplay();

These two lines call generatePassword() and updateLengthDisplay() when the page loads, ensuring that the user sees a default password and the current slider value immediately.

Put this CSS in head tag:

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

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f7fa;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            color: #333;
        }

        .page {
            background-color: #fff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
        }

        h1 {
            font-size: 24px;
            margin-bottom: 20px;
            text-align: center;
            color: #4CAF50;
        }

        .result-container {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }

        .result {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            background-color: #f0f0f0;
            border: 2px solid #ddd;
            border-radius: 8px;
            text-align: center;
            font-family: 'Courier New', Courier, monospace;
        }

        .copy-btn {
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .copy-btn:hover {
            background-color: #45a049;
        }

        .copy-btn:focus {
            outline: none;
        }

        .range-cont,
        .option-cont,
        .btn-cont {
            margin-bottom: 20px;
        }

        .password-length,
        label {
            font-size: 16px;
            color: #333;
            margin-bottom: 10px;
        }

        /* Small Password Length Display */
        #lengthDisplay {
            width: 50px;
            text-align: center;
            font-size: 14px;
            padding: 6px;
            border: 2px solid #4CAF50;
            border-radius: 5px;
            background-color: #f0f0f0;
            margin-top: 8px;
            margin-bottom: 8px;
            color: #333;
        }

        input[type="range"] {
            display: block;
            width: 100%;
            margin-top: 8px;
        }

        input[type="range"] {
            -webkit-appearance: none;
            appearance: none;
            height: 5px;
            background: #ddd;
            outline: none;
            border-radius: 5px;
        }

        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background: #4CAF50;
            cursor: pointer;
        }

        input[type="range"]::-moz-range-thumb {
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background: #4CAF50;
            cursor: pointer;
        }

        input[type="checkbox"] {
            margin-right: 10px;
        }

        .option-cont label {
            margin-bottom: 10px;
            display: block;
        }

        .btn {
            width: 100%;
            padding: 12px;
            background-color: #4CAF50;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .btn:hover {
            background-color: #45a049;
        }

        .btn:focus {
            outline: none;
        }

Here is the whole 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>Password Generator</title>
    <style>
        /* Global Style */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f7fa;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            color: #333;
        }

        .page {
            background-color: #fff;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
        }

        h1 {
            font-size: 24px;
            margin-bottom: 20px;
            text-align: center;
            color: #4CAF50;
        }

        .result-container {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }

        .result {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            background-color: #f0f0f0;
            border: 2px solid #ddd;
            border-radius: 8px;
            text-align: center;
            font-family: 'Courier New', Courier, monospace;
        }

        .copy-btn {
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .copy-btn:hover {
            background-color: #45a049;
        }

        .copy-btn:focus {
            outline: none;
        }

        .range-cont,
        .option-cont,
        .btn-cont {
            margin-bottom: 20px;
        }

        .password-length,
        label {
            font-size: 16px;
            color: #333;
            margin-bottom: 10px;
        }

        /* Small Password Length Display */
        #lengthDisplay {
            width: 50px;
            text-align: center;
            font-size: 14px;
            padding: 6px;
            border: 2px solid #4CAF50;
            border-radius: 5px;
            background-color: #f0f0f0;
            margin-top: 8px;
            margin-bottom: 8px;
            color: #333;
        }

        input[type="range"] {
            display: block;
            width: 100%;
            margin-top: 8px;
        }

        input[type="range"] {
            -webkit-appearance: none;
            appearance: none;
            height: 5px;
            background: #ddd;
            outline: none;
            border-radius: 5px;
        }

        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background: #4CAF50;
            cursor: pointer;
        }

        input[type="range"]::-moz-range-thumb {
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background: #4CAF50;
            cursor: pointer;
        }

        input[type="checkbox"] {
            margin-right: 10px;
        }

        .option-cont label {
            margin-bottom: 10px;
            display: block;
        }

        .btn {
            width: 100%;
            padding: 12px;
            background-color: #4CAF50;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .btn:hover {
            background-color: #45a049;
        }

        .btn:focus {
            outline: none;
        }
    </style>
</head>

<body>
    <div class="page">
        <div class="head-cont">
            <h1>Password Generator</h1>
        </div>

        <!-- Password display field with Copy button -->
        <div class="result-container">
            <input type="text" readonly id="passwordField" class="result" placeholder="Your password will appear here">
            <button class="copy-btn" onclick="copyPassword()">Copy</button>
        </div>

        <!-- Password length control -->
        <div class="range-cont">
            <p class="password-length">Password Length</p>
            <input type="text" id="lengthDisplay" readonly value="12">
            <input type="range" value="12" id="length" min="8" max="20" oninput="updateLengthDisplay()">
        </div>

        <!-- Options for password generation -->
        <div class="option-cont">
            <label><input type="checkbox" id="uppercase" checked> Uppercase</label>
            <label><input type="checkbox" id="lowercase" checked> Lowercase</label>
            <label><input type="checkbox" id="numbers" checked> Numbers</label>
            <label><input type="checkbox" id="symbols"> Symbols</label>
            <label><input type="checkbox" id="avoidAmbiguous"> Avoid Ambiguous</label>
        </div>

        <!-- Generate button -->
        <div class="btn-cont">
            <button onclick="generatePassword()" class="btn">Generate Password</button>
        </div>
    </div>

    <script>
        function generatePassword() {
            const length = document.getElementById('length').value;
            const includeUppercase = document.getElementById('uppercase').checked;
            const includeLowercase = document.getElementById('lowercase').checked;
            const includeNumbers = document.getElementById('numbers').checked;
            const includeSymbols = document.getElementById('symbols').checked;
            const avoidAmbiguous = document.getElementById('avoidAmbiguous').checked;

            // Character sets
            let uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            let lowercase = 'abcdefghijklmnopqrstuvwxyz';
            let numbers = '0123456789';
            let symbols = '!@#$%^&*()_+[]{}|;:,.<>?';
            let ambiguous = 'O0Il1';

            // Remove ambiguous characters if option is selected
            if (avoidAmbiguous) {
                uppercase = uppercase.replace(/[O]/g, '');
                lowercase = lowercase.replace(/[l]/g, '');
                numbers = numbers.replace(/[01]/g, '');
            }

            let charSet = '';
            if (includeUppercase) charSet += uppercase;
            if (includeLowercase) charSet += lowercase;
            if (includeNumbers) charSet += numbers;
            if (includeSymbols) charSet += symbols;

            if (charSet === '') {
                alert('Please select at least one option.');
                return;
            }

            let password = '';
            for (let i = 0; i < length; i++) {
                password += charSet.charAt(Math.floor(Math.random() * charSet.length));
            }

            // Display generated password in the text input field
            document.getElementById('passwordField').value = password;
        }

        function updateLengthDisplay() {
            const rangeValue = document.getElementById('length').value;
            document.getElementById('lengthDisplay').value = rangeValue;
        }

        function copyPassword() {
            const passwordField = document.getElementById('passwordField');
            passwordField.select();
            passwordField.setSelectionRange(0, 99999); // For mobile devices
            document.execCommand("copy");

            alert("Password copied to clipboard!");
        }

        // Initialize the display
        generatePassword();
        updateLengthDisplay();
    </script>
</body>

</html>

Conclusion

By following this guide, you now have a functional password generator with a clean UI, customizable options, and security features. This project not only improves your HTML, CSS, and JavaScript skills but also creates a practical tool you can use and expand further. A password generator like this is essential for enhancing online security, and knowing how to create one lets you customize it to your unique needs.

Creating tools that improve both usability and security is a rewarding experience. Experiment with different features, make the design your own, and explore more ways to improve your password generator!

Complete Code

The project is available on our GitHub : https://github.com/piehostHQ/password-generator

Comments

Anand Singh commented at

Posted on November 17th

This post has been deleted, only you can see it.

Test

Leave a comment.

Share your thoughts or ask a question to be added in the loop.