4

I have a function as below, which creates a strong password, however it does not always add a special character and a number or a capital letter to it, how do i ensure that it always has these requirements included in it.

The password requirements are that it has to

8 or more characters long and has to have a special character,a capital letter and a number included to it.

the function i have right now is displayed below

function GenPwd(nMinimumLength,bIsRequired,sNameoftheButton){
            var end=0;
            var index=0;
            var sPassCharactersWithoutSpeacil="!#$@*123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
            var sSpecialCharacters="!#$@*";
            var nSrngLen=sStrgStrAddOnChrs
            var sNumbers="123456789";
            var nMinimunLen=Math.round(nBaseLen/2);
            var PassWordDLength=Math.round((Math.random()*nMinLen)+nMinimumLength+nMinimumLength); //Make sure it is atleadt 8 characters long
            var Password="";
            var PasswordTemporary="";
            for(index = 1; index <= PassWordDLength; index++) {

                nCharacter = Math.round(Math.random()*65);

                 PasswordTemporary = sPassCharactersWithoutSpeacil.charAt(nCharacter);

                while (PWD.indexOf(PasswordTemporary) > -1) {
                    nCharacter = '';
                    nCharacter = Math.round(Math.random()*65);
                    PasswordTemporary = sPassCharactersWithoutSpeacil.charAt(nChar);
                }
                FinalPWD = Password + PasswordTemporary;
            }

this is what i have to use

function GenPwd(nBaseLen,bIsStrong,sBtnName){

        var end=0;
        var index=0;
        var sPassStr="!#$@*123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
        var sStrgStrAddOnChrs="!#$@*";
        var nSrngLen=sStrgStrAddOnChrs
        var sStrgStrAddOnNum="123456789";
        var nMinLen=Math.round(nBaseLen/2);
        var PWDLen=Math.round((Math.random()*nMinLen)+nBaseLen); 
        var PWD="";
        var PWDTmp="";
        //Generate the password
        for(index = 1; index <= PWDLen; index++) {

            nChar = Math.round(Math.random()*65);

            PWDTmp = sPassStr.charAt(nChar);

            while (PWD.indexOf(PWDTmp) > -1) {
                nChar = '';
                nChar = Math.round(Math.random()*65);
                PWDTmp = sPassStr.charAt(nChar);
            }
            PWD = PWD + PWDTmp;
        }

            document.getElementById("pwd").value=PWD;
        EnableBtn(sBtnName);
        return true;
    }
1
  • why not create a guid and then append Commented Jul 25, 2014 at 16:47

1 Answer 1

3

You can create a function that ensures your pwd contains at least one of a specific set of chars:

function ensurePwdContains(pwd, regexListOfChars, listOfChars) {
    if (!regexListOfChars.test(pwd)) {
        // select random char from listOfChars
        var newChar = listOfChars.charAt(Math.floor(Math.random() * listOfChars.length));

        // insert it into the current pwd in a random location
        // must do +1 to include the location at the end of the string
        var pos = Math.floor(Math.random() * (pwd.length + 1));
        pwd = pwd.slice(0, pos) + newChar + pwd.slice(pos);
    }
    return pwd;
}

This function will test to see if the password contains at least one instance of the regex passed in. If not, it will select a random character from the listOfChars argument and then insert that into the existing password in a random location.

And, then you call this function at the end of your function for each of your two cases:

FinalPwd = ensurePwdContains(FinalPwd, /[!#\$@*]/, sSpecialCharacters);
FinalPwd = ensurePwdContains(FinalPwd, /[A-Z]/, "ABCDEFGHIJKLMNOPQRSTUWXYZ");

Demo: http://jsfiddle.net/jfriend00/ur9FL/


And, here's a cleaned up version of your overall implementation. You were referring to a number of variables in your function that either aren't defined in your post or aren't used in your function so I removed those (since I don't know what they are or how they're used). Here's a bit cleaner implementation:

function generatePwd(minLen) {
    // create a pwd that is between minLen and ((2 * minLen) + 2) long
    // don't repeat any characters
    // require at least one special char and one capital char
    function rand(max) {
        return Math.floor(Math.random() * max);
    }

    function ensurePwdContains(pwd, regexListOfChars, listOfChars) {
        if (!regexListOfChars.test(pwd)) {
            var newChar = listOfChars.charAt(rand(listOfChars.length));
            var pos = rand(pwd.length + 1);
            pwd = pwd.slice(0, pos) + newChar + pwd.slice(pos);
        }
        return pwd;
    }

    var legalChars = "!#$@*123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ";
    var specialChars = "!#$@*";
    var specialRegex = /[!#\$@*]/;
    var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var capsRegex = /[A-Z]/;
    var nums = "123456789";
    var numRegex = /[1-9]/;

    // make legalChars into an array of chars (easier to deal with)
    legalChars = legalChars.split("");
    var pwd = "", len = minLen + rand(minLen), index;

    // ensure len is not too long
    len = Math.min(legalChars.length, len);

    // now add chars to the pwd string until it is of the desired length
    while (pwd.length < len) {
        index = rand(legalChars.length);
        pwd += legalChars[index];
        // remove the char we just used
        legalChars.splice(index, 1);
    }
    // ensure we have at least one special character and one caps char and one 1-9
    pwd = ensurePwdContains(pwd, specialRegex, specialChars);
    pwd = ensurePwdContains(pwd, capsRegex, caps);
    pwd = ensurePwdContains(pwd, numRegex, nums);
    return pwd;    
}

And, a working demo that generates a whole bunch of passwords so you can see what type of variation you get: http://jsfiddle.net/jfriend00/7dReY/


To put the password into place, I'd suggest you make a second function that calls the first function to generate the password and puts it into the field of choice:

function putPasswordInPlace(pwdId, sBtnName) {
     var pwd = generatePwd(8);
     document.getElementById(pwdId).value = pwd;
     EnableButton(sBtnName);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Man i have to use these three argument as you can see below, and i cant figure out where they exactly go. without the arguments that are passed here it will not work on the page with the button where the password is generated, i am sorry but this is a clear case of i have no idea what i am doing or i think i might know what i am doing
@user2799983 - Your code doesn't even use the bIsRequired or bIsStrong arguments you have in your question so I don't know what you want to do with those. If you want to describe, then desired behavior for those, I'm sure that functionality can be added too. I've created a second function (at the end of my answer) that takes the id of the password field and the sBtnName and carries out that extra part. This keeps the password generation function generic (so it can be used for other uses) and only the second function is specific to your page design (generally good coding practice).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.