使用Javascript将随机密码生成为具有输入长度的输入

时间:2017-06-03 14:45:48

标签: javascript

<form name="pgenerate">
<input type="text" size=18 name="output">
<input type="button" value="Generate Password" ><br />
<b>Password Length:</b> <input type="text" name="thelength" size=3 value="7">
</form>

如何制作随机密码生成器,在您可以在项目或系统中使用的输入中生成密码

3 个答案:

答案 0 :(得分:0)

&#13;
&#13;
var keylist="abcdefghijklmnopqrstuvwxyz123456789"
var temp=''
 
function generatepass(plength){
temp=''
for (i=0;i<plength;i++)
temp+=keylist.charAt(Math.floor(Math.random()*keylist.length))
return temp
}
 
function populateform(enterlength){
document.pgenerate.output.value=generatepass(enterlength)
}
&#13;
<form name="pgenerate">
<input type="text" size=18 name="output">
<input type="button" value="Generate Password" onClick="populateform(this.form.thelength.value)"><br />
<b>Password Length:</b> <input type="text" name="thelength" size=3 value="7">
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

无需重新发明轮子。看看这个库:https://www.npmjs.com/package/generate-password,它完全符合您的要求。

答案 2 :(得分:0)

试试这个纯JS解决方案:

function generateRandomPassword (passwordLength) {
    var outputPassword = "";
    var allPossibleChars  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < passwordLength; i++) {
        outputPassword += allPossibleChars.charAt(Math.floor(Math.random() * allPossibleChars.length));
    }
    return outputPassword;
}
<form name="pgenerate">
<input type="text" size=18 id="output" name="output">
<input type="button" value="Generate Password" onclick="document.getElementById('output').value = generateRandomPassword(document.getElementById('thelength').value);"><br />
<b>Password Length:</b> <input type="text" id="thelength" name="thelength" size=3 value="7">
</form>

如果您想添加更多可能的字符,只需更新allPossibleChars