我能够在 C# 中做到这一点,但无法将其转换为 Javascript。我找到了这篇文章“ Generate random password string with requirements in javascript ”,但我无法根据我的要求对其进行自定义:
密码长度应至少为 8 个字符,最多 13 个字符,并且必须包含以下每个字符串集合中的至少一个字符:
string specialCharacters = "~!@#$%^&*()_+=-|\\}]{[\"':;?/>.<,";
string numbers = "0123456789";
string smallLetters = "abcdefghijklmnopqrstuvwxyz";
string capitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
你能帮忙吗?非常感谢!
编辑:
这是我在 C# 中的代码。抱歉,有点长:
private string CreateRandomPassword(int passwordLength)
{
string specialCharacters = "~!@#$%^&*()_+=-|\\}]{[\"':;?/>.<,";
string numbers = "0123456789";
string smallLetters = "abcdefghijklmnopqrstuvwxyz";
string capitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string allowedChars = "";
char[] chars = new char[passwordLength];
string password = String.Empty;
Random rd = new Random();
int ctr = 0;
int prop = 4;
if(!_password.ContainsSpecialCharacters && !_password.ContainsNumbers && !_password.ContainsSmallLetters && !_password.ContainsCapitalLetters)
return String.Empty;
string sc = "";
string num = "";
string sl = "";
string cl = "";
if(_password.ContainsSpecialCharacters)
{
// Get a special character randomly
rd = new Random();
sc = specialCharacters[rd.Next(0, specialCharacters.Length)].ToString();
allowedChars += specialCharacters;
}
else
{
prop--;
}
if(_password.ContainsNumbers)
{
// Get a random number randomly
rd = new Random();
num = numbers[rd.Next(0, numbers.Length)].ToString();
allowedChars += numbers;
}
else
{
prop--;
}
if(_password.ContainsSmallLetters)
{
// Get a small letter randomly
rd = new Random();
sl = smallLetters[rd.Next(0, smallLetters.Length)].ToString();
allowedChars += smallLetters;
}
else
{
prop--;
}
if(_password.ContainsCapitalLetters)
{
// Get a capital letter randomly
rd = new Random();
cl = capitalLetters[rd.Next(0, capitalLetters.Length)].ToString();
allowedChars += capitalLetters;
}
else
{
prop--;
}
for (; ctr < passwordLength - prop; ctr++)
password += allowedChars[rd.Next(0, allowedChars.Length)];
return password + sc + num + sl + cl;
}