Generate a Password Using Vanilla JavaScript

Enforcing strong passwords can be challenging, but by providing users with an automated password generation feature, you can enhance both security and user experience.

HTML Structure

<p>
  <input type="text" name="password" id="password" placeholder="Password" value="">
  <a href="#" id="password-generate">Generate</a>
</p>

Note: The input type is set to “text” for illustrative purposes. When creating a new account and generating a password, it may be appropriate to use “password” as the input type to mask the characters.

JavaScript Implementation

// Function to generate a random password
function generatePassword(length = 12) {
  // Define character sets
  const lowercaseChars = 'abcdefghijklmnopqrstuvwxyz';
  const uppercaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const numberChars = '0123456789';
  const symbolChars = '!@#$%^&*()-_=+[]{}|;:,.<>?';

  // Combine all character sets
  const allChars = lowercaseChars + uppercaseChars + numberChars + symbolChars;

  let password = '';

  // Ensure the password includes at least one character from each set
  password += lowercaseChars.charAt(Math.floor(Math.random() * lowercaseChars.length));
  password += uppercaseChars.charAt(Math.floor(Math.random() * uppercaseChars.length));
  password += numberChars.charAt(Math.floor(Math.random() * numberChars.length));
  password += symbolChars.charAt(Math.floor(Math.random() * symbolChars.length));

  // Fill the remaining characters
  for (let i = password.length; i < length; i++) {
    password += allChars.charAt(Math.floor(Math.random() * allChars.length));
  }

  // Shuffle the password to prevent predictable patterns
  password = password.split('').sort(() => 0.5 - Math.random()).join('');

  return password;
}

// Event listener for the "Generate" link
document.getElementById('password-generate').addEventListener('click', function(e) {
  e.preventDefault(); // Prevent default link behavior

  const passwordField = document.getElementById('password');
  const newPassword = generatePassword(12); // Generate a 12-character password
  passwordField.value = newPassword; // Set the generated password in the input field
});

Character Sets: The function defines separate strings for lowercase letters, uppercase letters, numbers, and symbols. This allows for easy customization of the character sets used in password generation.

Ensuring Character Variety: To enhance password strength, the function ensures that the generated password includes at least one character from each character set.

Random Selection: The Math.random() function is used to select random characters from the combined character sets.

Shuffling: After assembling the password, the characters are shuffled to prevent any predictable patterns, especially since the first few characters are chosen from specific sets.

Event Handling: An event listener is attached to the “Generate” link, which, when clicked, generates a new password and populates the input field.

You can adjust the generatePassword function to:

  • Change the default password length by modifying the length parameter.
  • Include or exclude specific character sets based on your requirements.
  • Enhance randomness by using the Web Crypto API for cryptographically secure random values.

on in JavaScript DOM | Last modified on

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *