Password Generator with Javascript

Introduction

We all know the importance of making use of strong passwords either in our applications, websites, or whatsoever. A strong password provides essential protection from financial fraud and identity theft. One of the most common ways that hackers break into computers, applications, websites, e.t.c is by guessing passwords.

Simple and commonly used passwords enable intruders to easily gain access and control of a computing device.

In this article, you would learn how to generate random passwords with Javascript.

One amazing feature you would love is your:

  • Ability to decide the length of the password
  • Ability to select what your password should entail (e.g Only UpperCase Alphabets, alphabets, and symbols, e.t.c).

Getting Started

I wrote a very simple HTML code and CSS code just for User interface purposes Below is my simple HTML code:

<div class="container">
        <br>
        <p id="answer" class="answer"></p><br>    <br> -->    

        <center>
            <label>Length :</label>
            <input type="number" maxlength="100" value="20" id="length">
        </center>
        <br><br>
        <div class="checks">
            <label  class="label">Enable UpperCase Alphabets :</label>
            <input type="checkbox" id="upper" checked class="val"><br>
        </div>
        <div class="checks">
            <label  class="label">Enable LowerCase Alphabets :</label>
            <input type="checkbox" id="lower" checked class="val"><br>
        </div>
        <div class="checks">
            <label  class="label">Enable Numbers :</label>
            <input type="checkbox" id="number" checked class="val"><br>
        </div>
        <div class="checks">
            <label  class="label">Enable Symbols :</label>
            <input type="checkbox" id="symbol" checked class="val"><br><br>    
        </div>

        <center><button id="generate" class="btn">Generate</button></center>
    </div>

Going throught he html code you would descover some id like :

answer

This is where we would be displaying the random password generated.

length

This would help you or the users set the length of your password

Then we now have 4 checkboxes

upper // For uppercase

lower // For lowerCase

number // For Numbers

symbol // For Symbols 

This will allow you to checkboxes depending on what you want your password to consist of.

I hope with this you should perfectly understand the HTML code as we now to proceed to the Javascript code

Javascript

You can create a separate file for your Js code or just use the script tag to add to your HTML file.

The first thing we would do is to generate random values.

Generating Random values with Javascript

we would be making use of Character Sets Table i.e UTF-16 code units Table.

  • For UpperCase
      function getRandomUpperCase(){
        return String.fromCharCode(Math.floor(Math.random()*26)+65);
       }
    
  • For LowerCase
    function getRandomLowerCase(){
    return String.fromCharCode(Math.floor(Math.random()*26)+97);
    }
    
  • For Numbers

    function getRandomNumber(){
    return String.fromCharCode(Math.floor(Math.random()*10)+48);
    }
    

    Explaining the code above

    Math.random The Math.random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive).

    Math.floor The Math.floor() function in JavaScript is used to round off the number passed as a parameter to its nearest integer in Downward direction of rounding i.e. towards the lesser value.

    String.fromCharCode String.fromCharCode() function is used to create a string from the given sequence of UTF-16 code units.

Therefore putting these codes together helps us generate either random numbers, alphabets, e.t.c.

And finally , we also have to generate random symbols, this time around we wont make use of the table but i would list out the symbols i need, you can add your too.

function getRandomSymbol(){
    var symbol = "!@#$%^&*(){}[]=<>/,.|~?";
    return symbol[Math.floor(Math.random()*symbol.length)];
}

The next thing we have to do after Generating random variables is to communicate with our DOM

Since you already know all the id i declared in the HTML code, all we have to do is get them and store them in a variable.

//Communicating with the DOM

var answerEl = document.getElementById("answer");
var lengthEl = document.getElementById("length");
var numberEl = document.getElementById("number");
var lowerEl = document.getElementById("lower");
var upperEl = document.getElementById("upper");
var symbolEl = document.getElementById("symbol");
var copyEl = document.getElementById("copy");
var generateEl = document.getElementById("generate");

Once that is done we can declare a constant object where we could store the random values generated previously.

const randomFunc = {
    upper : getRandomUpperCase,
    lower : getRandomLowerCase,
    number : getRandomNumber,
    symbol : getRandomSymbol
};

Now we can generate an event so when the generate button us clicked the following code will run:smile:

//generate event
generateEl.addEventListener('click', () =>{
    const length = +lengthEl.value;
    const hasUpper = upperEl.checked;
    const hasLower = lowerEl.checked;
    const hasNumber = numberEl.checked;
    const hasSymbol = symbolEl.checked;

answerEl.innerText = generatePassword(hasUpper, hasLower, hasNumber, hasSymbol, length);
});

The answerEl.innerText simply means any thing this function returns would be displayed in the DOM which is the answer field I created.

If you study the code above proper you would discover I assigned constant variables to the values gotten from the DOM and then I went ahead to create a function which I would call below:

//Generate Password Function
function generatePassword(upper, lower, number, symbol, length){
    let generatedPassword = "";

    const typesCount = upper + lower + number + symbol;

    //console.log(typesCount);

    const typesArr = [{upper}, {lower}, {number}, {symbol}].filter(item => Object.values(item)[0]);

    if(typesCount === 0) {
        return '';
    }

    for(let i=0; i<length; i+=typesCount) {
        typesArr.forEach(type => {
            const funcName = Object.keys(type)[0];
            generatedPassword += randomFunc[funcName]();
        });
    }

    const finalPassword = generatedPassword.slice(0, length);


    return finalPassword;
}

The above code will be returned to the answerEl variable which would now be displayed in the DOM.

Conclusion

We all know the advantages of having complex passwords people would not easily guess. This could be integrated into whatsoever application or website you are building, I would be so glad to hear project ideas and many other cool kinds of stuff.

You can test this out live here and if you think its cool, kindly give a star on github(contributions are also welcome).

p.s: I'm looking forward to being your friend:rocket: let's connect on twitter.

Useful Resources