Monday, September 26, 2022

Build a Configurable Random Password Generator With JavaScript

Build a Configurable Random Password Generator With JavaScript

Password generators are a common sight on the web these days. Websites often won’t allow you to create an account without a secure enough password. In this tutorial, we’ll build a random password generator with JavaScript that can be configured on the fly.

Our JavaScript Password Generator

Here’s a preview of the tool we’ll be building in this tutorial. The three settings allow you to:

  • Define the password length
  • Define whether or not numbers will be included in the result
  • Define whether or not symbols will be included in the result

Click on Generate to get a random password, then click Copy to copy it to your clipboard!

This is an intermediate level tutorial, although it’s explained in such a way that even beginners can follow along. The best way to learn is to do!

The Password Tool’s UI

Let’s begin by building a UI with HTML and CSS, then we’ll address the JavaScript once that’s done.

1. The HTML

Using some basic HTML and CSS, I’ll start by adding a set of controls and CSS styles the generator will use. Below is the main HTML markup.

The generator has a text input where the final password will display and a set of controls to configure the password character types, including numbers, symbols, and length. There’s a Generate button and a Copy button to make it easy to grab the password for quick use.

For the body of the page I’ll use a Google font called Lexend. I added the following code within the head tags of the HTML page so the font renders.

2. The CSS

The CSS I added is as follows.

You’ll see I’ve added a gradient for the main background. I also used newer CSS variables to avoid repeating myself in a few spots concerning colors.

info
We’ll add an alert confirmation for the Copy button with JavaScript. For now, there is CSS to support it when we reach that point of the tutorial.

So far we’ve built a static HTML and CSS UI template:

Adding Behavior With JavaScript

Generating random characters, strings, and numbers in JavaScript can be accomplished using built-in features of the JavaScript API. These are confusing at first glance, but with enough practice, you can become more comfortable with them in no time.

1. Target HTML Elements

I’ll start by targeting all the necessary HTML elements using unique identifiers. Those will live at the top of my JavaScript file.

Refer to the HTML with the ID of what we pass for each constant variable above. We’ll need to target all the form elements and controls, and there are quite a few!

We can begin by setting up the password length field with the variables in place. This is an HTML range input. We can manipulate it with JavaScript and display the current setting as it updates.

If the range slider is changed, I want to update the number displayed on the page to reflect it. This number is purely a visual enhancement, so the end user knows firsthand the number of characters they are configuring their password.

2. Randomizing Functions

Next up, we’ll add a set of functions we can call that will return randomized values based on what gets configured.

Let me start by saying I know these are very confusing to understand! Each function returns a string value. The built-in String.fromCharCode method can create a new string from an existing character code. This means a string character can symbolize a number added.

To make more sense of this, you can open your browser’s console tab and paste the return line from one of these functions. Change the number at the end, and you should see new characters appear each time it runs.

console log in firefoxconsole log in firefoxconsole log in firefox
Repeatedly outputting randomize function using console.log()

Using JavaScript’s Math.floor() and Math.random() we can be sure we return unique characters each time.

3. Iterate Over Password Length, Adding Generated Characters

Let’s now iterate over a loop in JavaScript, based on the password length configured, and use our randomly generated characters.

The code above is triggered when the Generate button gets clicked. We get the values of the fields we’ve already queried for and pass those to a new function called generatePassword. This function returns a unique password we assign to the final result input for use.

The generatePassword function accepts three parameters, number, symbol, and length, which map to the controls on our generator form.

This part gets confusing, but inside the function, we use a for loop that cycles through the length the password gets configured to be. So if the password were twenty characters, it would loop twenty times.

During each iteration, we can check if the checkbox values for the number or symbol options are checked. If they are checked, we add to and assign a variable called generatedPassword that initially had no value.

This new value can be assigned and reassigned based on the options set and the current iteration of the loop.

By default, we’ll always include lowercase letters in the password generator so that line comes last without any conditional statement.

Finally, we’ll slice() the password at the length that it gets configured for and return the newly generated password..

Still with me? The hard part is over, I promise.

4. Click to Copy (User Experience)

What’s a password generator without a handy way to copy the generated password? To enhance our tool, we can use JavaScript to tap into some internal APIs. This will dynamically copy the text from the result input.

To correctly copy the password with the click of a button, we’ll need to create a new input field, select the area dynamically, copy the password into it and then quickly remove it from the page to make this all work well.

You might think this seems complex and clunky, and I’d 100% agree with you, but it works pretty well and is pretty secure.

To piggyback on this code, I’ve added a small alert piece of UI we can dynamically add and remove after a short period. This is all done by creating HTML with JavaScript and removing it quickly from view after the “copying” action is complete.

If you recall, I added a .alert class with some styles back to our CSS. Here is where that all comes into play.

5. Generate a Password on the First Page Load

Until now, you’ve needed to click the Generate button to get a generated password to appear. I think it would be nice if one appeared as soon as you loaded the page. We can reuse the generatePassword function and set a few new variables to make this a reality, and I’ll also set a default password length on page load.

6. Tying it All Together!

Here’s all the JavaScript in its final form. There is a decent amount of code here, but I hope it isn’t too daunting. This password generator could be great for a sign-up form to help convince users to opt-in for a stronger password.

Conclusion

And we’re done! Let’s remind ourselves what we’ve built:

This code has a considerable amount of complexity, so don’t feel you need to understand it all if you are a JavaScript novice. However I hope this tutorial helped you make sense of some advanced use cases for JavaScript, and empowers you to keep building.

If you get confused, take a step back and search the web for some built-in methods like Math.floor() and the approaches seen here. With enough practice and repetition, using these built-in methods will come naturally!


No comments:

Post a Comment