avanti said:
Hi,
I need to generate random alphanumeric password strings for the users
in my application using Javascript. Are there any links that will have
pointers on the same?
Thanks,
Avanti
Below is a script I wrote a while ago which generates random
alphanumeric strings. The concept is widely used and definitely not
novel to this code. Warning: It uses the Prototype.js class construct.
You could easily rewrite it to avoid that though.
//
// Generates random alphanumeric strings.
//
Generator = Class.create();
Generator.prototype = {
// Properties.
aConsLow:['b','c','d','f','g','h','j','k','l',
'm','n','p','q','r','s','t','v','w','x','y','z'],
aConsUp:['B','C','D','F','G','H','J','K','L',
'M','N','P','Q','R','S','T','V','W','X','Y','Z'],
aHardConsLow:['b','c','d','f','g','h',
'k','m','p','s','t','v','z'],
aHardConsUp:['B','C','D','F','G','H',
'K','M','P','S','T','V','Z'],
aLinkConsLow:['h','l','r'],
aLinkConsUp:['H','L','R'],
aVowelsLow:['a','e','i','o','u'],
aVowelsUp:['A','E','I','U'],
aDigits:['1','2','3','4','5','6','7','8','9'],
// Constructor.
initialize:function() {
this.CallRandom(new Date().getSeconds());
this.aFormat = [this.aConsLow, this.aConsUp, this.aDigits,
this.aHardConsLow, this.aHardConsUp, this.aDigits,
this.aLinkConsLow, this.aLinkConsUp, this.aDigits,
this.aVowelsLow, this.aVowelsUp, this.aDigits];
},
// Calls Math.random() the given number of times and returns the
// result of the last call.
CallRandom:function(iCount) {
while(iCount - 1 > 0) {
Math.random();
--iCount;
}
return Math.random();
},
// Gets a random index in aFrom.
GetRandomIndex:function(aFrom) {
return Math.floor(this.CallRandom(new Date().getSeconds()) *
aFrom.length);
},
// Gets a random item in aFrom.
GetRandomItem:function(aFrom) {
return aFrom[this.GetRandomIndex(aFrom)];
},
// Generates and returns a password of the given length;
Generate:function(iLength) {
var sPw = "";
while(iLength > 0) {
sPw += this.GetRandomItem(
this.aFormat[
this.GetRandomIndex(this.aFormat)
]
);
--iLength;
}
return sPw;
}
};
Cheers!
Chad