DEV Community

Cornea Florin
Cornea Florin

Posted on

Vue Js 2 - password generator (vue04)

Vue Js 2 password generator

The codepen result

I developed a small app for generating random strings in vuejs

I wanted to keep it as simple as possible so the most complex part is the algorithm for generating the "random" string

Let's explain the password generator code

The idea was to generate dynamic passwords based on some options like the length of the generated password and the characters it includes

First i declared what was needed

data: function() { return { characters: [ { name: "Lowercase", value: "abcdefghijklmnopqrstuvwxyz", checked: false, }, { name: "Uppercase", value: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", checked: true, }, { name: "Numbers", value: "0123456789", checked: true, }, { name: "Special Characters", value: "_-+=)(*&^%$#@!`~", checked: false, }, ], password: "", gLength: 9, } }

After that i made a method that fires when the "Generate" button is clicked. Inside that function i added a loop where i concatenated the values of the checked options for characters

Now that we have our custom options, let's begin the magic :))

The idea is to loop and find a new random character until the length option is acquired

This being said, let's loop as many times as we setted up our generator length

for ( var i = 0; i < this.gLength; i++ ) { }

At each pass we need to add a new "random" character to the result, for this we are going to pick up a character from a specific location using the charAt() function. This function accepts an integer so we need to make sure we are selecting a random one

To make sure we are getting an integer, we are going to use the Math.floor() function, so now we have smth like this: ourString.charAt(Math.floor())

Now let's create the random number and for that we are going to use the Math.random() and also we need to multiply it to to the our characters string length to make sure we not get a position that doesn't exist

The code looks like this

for ( var i = 0; i < this.gLength; i++ ) { result += charactersVal.charAt(Math.floor(Math.random() * charactersVal.length)); } this.password = result;

Different design approach

Top comments (0)