Password Generator with js
Tags: webdev, javascript, beginners, programming
Published: 2023-02-08 02:28:16

Using JavaScript, let's create a Password Generator

## Code 

### HTML

```html
<h2>Password Generator</h2>
<fieldset>
  <legend>Password</legend>
  <div id="resultEl"></div>
  <button id="generateEl">Generate password</button>
</fieldset>
<fieldset>
  <legend>Length</legend>
  <label>Length</label>
  <input type="number" id="lengthEl" min="1" />
</fieldset>
<fieldset>
  <legend>Include</legend>
  <div>
    <label>uppercase</label>
    <input type="checkbox" id="uppercaseEl" checked />
  </div>
  <div>
    <label>lowercase</label>
    <input type="checkbox" id="lowercaseEl" checked />
  </div>
  <div>
    <label>numbers</label>
    <input type="checkbox" id="numberEl" checked />
  </div>
  <div>
    <label>symbols</label>
    <input type="checkbox" id="symbolEl" checked />
  </div>
</fieldset>
```

The user can define the length of the password to be generated using a numerical input field. It is also possible to select which types of characters should be included in the password: uppercase letters, lowercase letters, numbers and symbols. The "Generate Password" button is used to start the password generation process. The result of generating the password is displayed in a div with the ID "resultEl".

### JS

The following code is a password generator that allows users to specify the length and character types of the password.

## Function: generatePassword

```js
generateEl.addEventListener('click', generatePassword);
```

This function is triggered when the user clicks the "Generate password" button. It starts by defining an object called randomFunc:

```js
let randomFunc = {
    randomLower: () => tableASCII(26, 97),
    randomUpper: () => tableASCII(26, 65),
    randomNumber: () => tableASCII(10, 48),
    randomSymbol: () => randomSymbol(),
  };
```

randomFunc has four properties, each of which refers to a function that returns a random character:

* **randomLower** returns a random lowercase letter
* **randomUpper** returns a random uppercase letter
* **randomNumber** returns a random number
* **randomSymbol** returns a random symbol

The function then checks if the user has selected each of these options by checking the state of the corresponding checkboxes:

```js
!lowercaseEl.checked && delete randomFunc.randomLower;
!uppercaseEl.checked && delete randomFunc.randomUpper;
!numberEl.checked && delete randomFunc.randomNumber;
!symbolEl.checked && delete randomFunc.randomSymbol;
```

If the user has not selected a certain option, the corresponding property is deleted from the randomFunc object. This ensures that the password only contains the characters that the user has selected.

Finally, the function calls the `randomPassword` function and passes the length of the password and the `randomFunc` object as arguments:

```js
resultEl.innerText = randomPassword(lengthEl.value, randomFunc);
```

## Function: randomPassword

The `randomPassword` function generates the password by looping through the desired length and concatenating a random character generated by the `randomObject` function.

```js
function randomPassword(length, randomFunc) {
  try {
    let generatedPassword = '';
    for (let i = 0; i < length; i++) {
      generatedPassword += randomObject(randomFunc)();
    }
    return generatedPassword;
  } catch (e) {
    console.warn(e);
    return 'Marque pelo menos um item';
  }
}
```

## Function: randomObject

The `randomObject` function takes an object as an argument and returns a random property from that object.

```js
const randomObject = (obj) =>
obj[Object.keys(obj)[Math.floor(Math.random() * Object.keys(obj).length)]];
```

## Function: tableASCII

The `tableASCII` function is used to generate random characters from the ASCII table. It takes two arguments: the number of characters in the table and the starting character code.

```js
const tableASCII = (ini, start) =>
String.fromCharCode(Math.floor(Math.random() * ini) + start);
```

## Function: randomSymbol

The `randomSymbol` function returns a random symbol from a predefined string of symbols.

```js
function randomSymbol() {
  const symbols = '
```

## Demo

See below for the complete working project.

{% codepen https://codepen.io/WalterNascimento/pen/OJbvwpO %}


_💡 NOTE: If you can't see it [click here](https://codepen.io/WalterNascimento/pen/OJbvwpO ) and see the final result_


***

## Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊

***

## Support Me

[Youtube - WalterNascimentoBarroso](https://www.youtube.com/channel/UCXm0xRtDRrdnvkW24WmkBqA)
[Github - WalterNascimentoBarroso](https://github.com/walternascimentobarroso)
[Codepen - WalterNascimentoBarroso](https://codepen.io)