Yesterday one of my friend contacted me for a simple JavaScript password generator that he wants to use in their Intranet.
Like everyone I thought of depending on Google, but after hearing his requirements I thought of making one myself. The code may seem bit specific as I’ve done this for a very specific requirement.
function generatePassword(type, plen){
var lwrAlph = "abcdefghijklmnopqrstuvwxyz",
uprAlph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
nums = "0123456789",
spl = "~!@#$%^&*()-_=+|<>,.;:[]{}",
passwd = [],
maxLen = 32,
defLen = 8,
minLen = 5;
/*Parameter Manipulations*/
type = type || "all";
type = isNaN(type)?type.toLowerCase():"all";
plen = plen || defLen;
plen = (plen < 0?defLen:(plen <= maxLen? (plen < minLen?defLen:plen): maxLen));
/*Choosing the password source characters*/
src = type === "alpha"? [lwrAlph, uprAlph]:type === "alphanum"?[lwrAlph, uprAlph, nums]:[lwrAlph, uprAlph, nums, spl];
/*Password construction*/
for (var i = 0; i < plen; i++) {
var rnd = Math.floor(Math.random() * src.length),
charBuild = src[rnd].split("");
rnd = Math.floor(Math.random() * charBuild.length);
passwd.push(charBuild[rnd]);
}
return passwd.join("");
}
The function accepts two parameters. The first one denotes type, which tells the routine what kind of characters should be used. This parameter can have 3 possible values: all, alpha and alphanum.
If you use value all the generated password can use alaphabets (lower & upper), numbers and special characters.
If you use alpha the generated password can use alaphabets (lower & upper).
If you use alphanum the generated password can use alaphabets (lower & upper) and numbers.
The second parameter denotes the length of the password going to generate. It has a restriction of 32 characters maximum and 5 characters minimum. If the user do not specify the length the a length would be selected by the code, which is 8. So it might be bit confusing at first but it is straight one once you check the logic.
I have furnished some test function calls that I’ve done earlier during a small testing period.
console.log(generatePassword("", -1));
console.log(generatePassword(""));
console.log(generatePassword());
console.log(generatePassword(null, null));
console.log(generatePassword(undefined, undefined));
console.log(generatePassword("alpha", 8));
console.log(generatePassword("alphanum", 8));
console.log(generatePassword("alphanum", 33));
console.log(generatePassword(-1));
console.log(generatePassword(1));
console.log(generatePassword("alphanum", 3));
I was using my Firebug console for checking the outputs of the function.