JavaScript Password Generator with Rules

JavaScript Password Generator with Rules
Code Snippet:Password générator, pure javascript
Author: Julien Az
Published: January 14, 2024
Last Updated: January 22, 2024
Downloads: 531
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a user-friendly password generator. It lets you customize password length and criteria (lowercase, uppercase, numbers, symbols) for secure and tailored password generation. The core function is to generate and display passwords based on user-defined rules. It’s a handy tool for quickly generating strong passwords.

It’s helpful for user registration or password reset forms, ensuring users create robust and unique passwords.

How to Create a Password Generator with Rules using JavaScript

1. Start by creating the HTML structure for your password generator. You can place this code inside your HTML file.

<div id="password-generator">

    <input value="Password generator" id="password-output">

    <div class="range">
      <input 
        type="range"
        min="4"
        max="24"
        step="1"
        value="8"
        id="password-length"
        oninput="document.getElementById('display-password-length').value=this.value"
      >
      <input 
        type="text"
        value="8"
        maxlength="2"
        id="display-password-length"
        oninput="document.getElementById('password-length').value=this.value"
      >
    </div>

    <div class="flex">
      <input type="checkbox" id="lowercase" checked="checked">
      <label for="lowercase">a-z</label>

      <input type="checkbox" id="uppercase">
      <label for="uppercase">A-Z</label>

      <input type="checkbox" id="numbers">
      <label for="numbers">0-9</label>

      <input type="checkbox" id="symbols">
      <label for="symbols">!-?</label>
    </div>

    <button id="generateButton" type="button" onclick="generatePassword()">Generate</button>

  </div>

2. Use the following CSS code to style your password generator. This CSS code ensures a visually appealing and user-friendly interface.

@import url("https://fonts.googleapis.com/css?family=Cuprum&display=swap");
* {
  box-sizing: border-box;
  font-family: "Cuprum", sans-serif;
}

input {
  border: none;
  background: transparent;
  outline: none;
}

body {
  overflow: hidden;
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  text-align: center;
  height: 100vh;
  background: #F44336;
}
body #password-generator {
  padding: 2rem;
  margin: 0 auto;
  width: 500px;
  border-radius: 3px;
  box-shadow: 0 0 2px #1f1f1f;
  border: 3px solid #d5d4ff;
  position: relative;
  white-space: nowrap;
}
body #password-generator #password-output {
  text-align: center;
  font-size: 2.5rem;
  margin: 0 auto 1.2rem;
  width: 100%;
}
body #password-generator .range {
  justify-content: space-between;
  padding: 1rem 1rem 1rem 2.5rem;
}
body #password-generator .range input[type=range] {
  -webkit-appearance: none;
  appearance: none;
  width: 40%;
  max-width: 100%;
  height: 15px;
  padding: 0px;
  background: #d5d4ff;
  outline: none;
  opacity: 0.7;
  -webkit-transition: 0.2s;
  transition: opacity 0.2s;
  box-shadow: 0 2px 35px rgba(0, 0, 0, 0.4555);
  border-radius: 10px;
  cursor: pointer;
  scroll-behavior: smooth;
  z-index: 1;
}
body #password-generator .range input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 15px;
  height: 15px;
  background: black;
  cursor: pointer;
  border-radius: 18px;
  transition: 0.5s ease;
}
body #password-generator .range input[type=range]::-webkit-slider-thumb:focus, body #password-generator .range input[type=range]::-webkit-slider-thumb:active {
  padding: 16px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.25);
}
body #password-generator .range #display-password-length {
  text-align: center;
  font-size: 1.4rem;
  width: 80px;
  padding-top: 10px;
}
body #password-generator .flex {
  margin: 1rem 1rem 2rem;
  display: flex;
  justify-content: space-between;
}
body #password-generator .flex input {
  display: none;
}
body #password-generator .flex input:checked + label {
  background: #d5d4ff;
  filter: brightness(120%);
  transform: scale(1.1);
}
body #password-generator .flex label {
  border: 2px solid #d5d4ff;
  border-radius: 4px;
  padding: 0.8rem;
  cursor: pointer;
  font-size: 1.3rem;
  text-align: center;
  display: block;
  width: 80px;
  transition: 0.2s ease;
}
body #password-generator .flex label:hover {
  filter: sepia(70%);
}
body #password-generator button {
  outline: none;
  background: #d5d4ff;
  border: none;
  padding: 1rem 2rem;
  margin: 0.5rem 0;
  border-radius: 3px;
  box-shadow: 1px 1px 3px #1f1f1f;
  text-transform: uppercase;
  font-size: 1.2rem;
  transition: 0.2s ease;
  cursor: pointer;
}
body #password-generator button:hover {
  transform: translateX(4px);
  filter: brightness(120%);
}

3. Finally, add the JavaScript logic to make the password generator functional. This code defines the password criteria and generates the password accordingly.

const passwordOutput =  document.getElementById('password-output');
const dataLowercase = "azertyuiopqsdfghjklmwxcvbn".split('');
const dataUppercase = "AZERTYUIOPQSDFGHJKLMWXCVBN".split('');
const dataNumbers = "0123456789".split('');
const dataSymbols = "!@#$%^&*-_=+\|:;',.>/?~".split('');

function generatePassword() {

  const data = [].concat(
    lowercase.checked ? dataLowercase : [],
    uppercase.checked ? dataUppercase : [],
    numbers.checked ? dataNumbers : [],
    symbols.checked ? dataSymbols : []
  );

  let passwordLength = parseInt(document.getElementById('display-password-length').value);
  let newPassword = '';

  if (data.length === 0) {
    passwordOutput.innerHTML = "Générateur de MDP";
    alert('Please check at least one criteria');
    return;
  }

  for (let i = 0; i < passwordLength; i++) {
    newPassword += data[Math.floor(Math.random() * data.length)];
  }
  passwordOutput.value = newPassword;
  
  passwordOutput.select();
  document.execCommand('copy');
  generateButton.innerHTML = "Copied !";
  setTimeout(() => {generateButton.innerHTML = "Générer mot de passe"}, 3500);

}

You can customize this code by adding more criteria or changing the styling to match your website or application’s design. Once you’re satisfied, integrate it into your project, and ensure the “generatePassword()” function is called when the user clicks the “Generate” button.

That’s it! hopefully, you have successfully created a JavaScript Password Generator With Rules. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X