0

I'm trying to create a simple javascript password generator that spits out the number of characters the user puts in. So, lets say you enter the number 7. I want the program to then spit out 7 random characters from the possibilities variable. Below is my code so far:

var possibilities = ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'J', 'K', 'L',
  'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
  'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
  'y', 'z', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
];

var special_chars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?"; //no special     characters

function generator() {

  if (document.getElementById("input").value == '' || document.getElementById("input").value > 61) {

    alert("Enter under 61 characters");

  } else if (isNaN(document.getElementById("input").value) || document.getElementById("input").value == special_chars) {

    alert("Enter numbers only");
  } else {
    //var userInput = document.getElementById("input").value -- get value of this when clicked, spit out number of items from this array based on the value collected

    for (var x = 0; x < possibilities.length; x++) {

      var content = possibilities[Math.floor(Math.random() * possibilities.length)];
    }

    document.getElementById("random_password").innerHTML = content;
  }

}

I'm a bit new to JavaScript and am kind of stuck here so any help is appreciated :) Thx in advance!

Banana
  • 7,424
  • 3
  • 22
  • 43
Shakira
  • 9
  • 1
  • 3
  • you forgot to mention whats wrong with your code – Banana Mar 10 '15 at 18:07
  • Take a look at this, it should slim down your function and you can use this with very few changes. http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript#answer-1349426 – NewToJS Mar 10 '15 at 18:09
  • oops @Banana when I run this, it just spits out one random letter from the possibilities array – Shakira Mar 10 '15 at 18:13
  • `== special_chars` will test if the input is exactly equal to that string, it doesn't test whether it contains any of them. Use a regular expression for that. – Barmar Mar 10 '15 at 18:13
  • Where are you using the input number as the count of characters to generate? Why are you using the length of the possibilities array as the number of times to loop? – Barmar Mar 10 '15 at 18:13
  • @Shakira well first of all, you need to do some reading about programming... there are some very basic understanding issues in your code... a nice place to start could be [Here](http://www.w3schools.com/) – Banana Mar 10 '15 at 18:16

4 Answers4

1

Here is a working demo. This is uses an existing answer found here. I have added minor changes to fit this question.

function makeid(){
var IdLength=document.getElementById('IdLength');
//Strip anything but 0 to 9
var UserInput=IdLength.value.replace(/[^0-9.]/g, "");
//Update input value
IdLength.value=UserInput;
var Results=document.getElementById('results');
var text = "";
var shuffle = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//Is input is empty?
if(IdLength!==''){
 for( var i=0; i < IdLength.value; i++ ){
     text += shuffle.charAt(Math.floor(Math.random() * shuffle.length));
    }
    Results.innerHTML=text;
}
}
<input type="text" id="IdLength" oninput="makeid()" placeholder="Enter 0-9"/>
<span id="results"></span>

I hope this helps. Happy coding!

Community
  • 1
  • 1
NewToJS
  • 2,762
  • 3
  • 14
  • 22
  • Many Thanks @NewToJS Sorry if this is a noob question but exactly what is "event.target.value;" doing in the for loop? – Shakira Mar 10 '15 at 18:41
  • @Shakira he assumed that you will call this function on keydown/change event of the input, and `event.target.value` is simply a reference to the value of the element that fired the event. – Banana Mar 10 '15 at 19:00
  • @Banana I didn't *assume* anything. This is a demo, i don't have the full source code so i have put this into something simple *for demo use*. Comments are in place to explain the function. @Shakira; This is where you have to put some work in and work out how to put this into your existing source code (if you want to use this). – NewToJS Mar 10 '15 at 19:09
  • @NewToJS dont get so defensive, did i say that assuming was bad? – Banana Mar 10 '15 at 19:11
  • @Shakira thank you for pointing that out, you can remove `event.target.value` I edited this a few times and didn't remove that. I will update it now. It should be `IdLength.value` – NewToJS Mar 10 '15 at 19:12
  • @Banana I'm not being defensive, i'm explaining the reason for my answer and pointing out no assumptions were made. – NewToJS Mar 10 '15 at 19:26
0

If you are looking for something basic then you should try the Jen library (works both on browsers and nodejs/io.js).

And actually it is not recommended to use Math.random() for crypto application (such as password generation)

0

This is a small script that I wrote. I do use this on a day to day basis to generate passwords. It is not perfect but it will do the small tasks. Feel free to play around with it and make it more perfect.

This is the JavaScript code plus the HTML code so you can try it. Basically, you can give Length anything that is a string(I haven't make an error checking for that). If the length is equal to 'rand' then the generator will generate a random password with a length between 19 to 30 characters. If length can't be converted to a number or is lower than 13 then the password generator will generate a password with a length of 13.

For the variable "not" and the feature of "Not". The password generator will not generate a password that contained any character that you placed in the Not field.

When it comes to generating the password, the generator will generate one character for each variable of s, n, u, l(4 in total). It will then generate the rest of it length randomly using the characters from variable a. After that, the generator will shuffle the string that it just generated randomly. It will then alert you the length of the password and give the output of the password in the shadowed box.

Also, it is just easier to obtain a random character at a random position in the string then taking a character from a random index in an array. It is easier when it comes to reconfiguring the script.

<html>
<head>
<script type="text/javascript">
function rand( len, not ){
    if ( len === undefined ) len = 13;
    if ( typeof not !== 'string' ) not = '';
    if ( len === 'rand' ) len = Math.floor(Math.random() * (30 - 19) + 19);
    if ( typeof len === 'string' ) len = parseInt(len, 10);
    if ( len < 13 || isNaN(len)  ) len = 13;

    var s = '!@~!@#$%^&*()-_=+',
        n = '0123456789',
        u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        l = 'abcdefghijklmnopqrstuvwxyz',
        a = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@~!@#$%^&*()-_=+',
      out = '';

    if ( (nl = not.length) > 0 ){
        var regex = '';
        for ( var i = 0; i < nl; i++ ){
            regex = not.charAt(i).replace(/[.*+?^${}()|[\]\\]/, '\\$&');
            regex = new RegExp( regex , 'g');
            if ( s.length > 0 ) s = s.replace( regex, '');
            if ( n.length > 0 ) n = n.replace( regex, '');
            if ( u.length > 0 ) u = u.replace( regex, '');
            if ( l.length > 0 ) l = l.replace( regex, '');
            a = a.replace( regex, '');
        }
    }

    if ( s.length > 0 ) out += s.charAt( Math.floor(Math.random() * s.length) );
    if ( n.length > 0 ) out += n.charAt( Math.floor(Math.random() * n.length) );
    if ( u.length > 0 ) out += u.charAt( Math.floor(Math.random() * u.length) );
    if ( l.length > 0 ) out += l.charAt( Math.floor(Math.random() * l.length) );

    for ( var i = out.length; i < len; i++) out += a.charAt( Math.floor(Math.random() * a.length) );


    out = out.split('').sort(function(a, b){return 0.5 - Math.random()}).join('');
    alert(out.length);
    return out;
}

function generate(){
    document.getElementById("result").value = rand( document.getElementById("length").value, document.getElementById("not").value );
}

</script></head>
<body>

<label for="length">Length:</label><input type="text" id="length" maxlength="5" size="5">
<label for="not">Not:</label><input type="text" id="not" size="12">
<button onclick="generate();" type="button">Generate</button><br />

<input type="text" id="result" size="35" value="Result" disabled><br />


</body>
</html>
Kevin Ng
  • 2,146
  • 1
  • 13
  • 18
0

Memorable password generator

// Also you can use a custom function to get random numbers instead
const _ = require('lodash/number');

/*
 * Generate comfortable to remember password
 *
 * @param integer length - length of generated password
 *
 * @return string password
 */
function my_create_password(length)
{
    let vowel = [
        'a',
        'e',
        'i',
        'o',
        'u',
    ];

    let consonant = [
        'b',
        'c',
        'd',
        'f',
        'g',
        'h',
        'j',
        'k',
        'l',
        'm',
        'n',
        'p',
        'q',
        'r',
        's',
        't',
        'v',
        'w',
        'x',
        'y',
        'z',
    ];

    result = '';
    for (let i = 0; i < length; i++) {
        if (i % 2 === 0) {
            result += consonant[_.random(0, 15)];
        } else {
            result += vowel[_.random(0, 4)];
        }
    }

    return result;
}

Result:

password(8);//kutekaku
password(11);//rahubabatun