我想验证密码是否在javascript中输入,并让用户知道何时满足每个要求。
到目前为止,我的js代码是
//Test password as its being typed
$(document).ready(function () {
$("#password").keyup(ValidatePassword);
});
//recieve password
function ValidatePassword() {
var password = $("#password").val();
}
我有一个cs函数来验证我希望在传递此函数时最终调用的密码。
以下是我正在使用的验证:
ublic static bool ValidatePassword(string password)
{
const int MIN_LENGTH = 8;
const int MAX_LENGTH = 50;
if (password == null) throw new ArgumentNullException();
bool meetsLengthRequirements = password.Length >= MIN_LENGTH && password.Length <= MAX_LENGTH;
bool hasUpperCaseLetter = false;
bool hasLowerCaseLetter = false;
bool hasDecimalDigit = false;
if (meetsLengthRequirements)
{
foreach (char c in password)
{
if (char.IsUpper(c)) hasUpperCaseLetter = true;
else if (char.IsLower(c)) hasLowerCaseLetter = true;
else if (char.IsDigit(c)) hasDecimalDigit = true;
}
}
bool isValid = meetsLengthRequirements
&& hasUpperCaseLetter
&& hasLowerCaseLetter
&& hasDecimalDigit
;
return isValid;
}
我基本上想在javascript中使用这个,所以我可以验证吗?
答案 0 :(得分:1)
尝试以下代码,
function ValidatePassword() {
var password = $("#password").val();
var lowerCaseLetters = /[a-z]/g;
if (password.value.match(lowerCaseLetters)) {
} else {
}
// Validate capital letters
var upperCaseLetters = /[A-Z]/g;
if (password.value.match(upperCaseLetters)) {
} else {
}
// Validate numbers
var numbers = /[0-9]/g;
if (password.value.match(numbers)) {
} else {
}
// Validate special characters
var specialChar = /[@#$%]/g;
if (password.value.match(specialChar)) {
} else {
}
// Validate length
if (password.value.length == 8) {
} else {
}
}
答案 1 :(得分:1)
以下是C#的直接翻译,如果有帮助
function validatePassword(password) {
const minLength = 8, maxLength = 50;
if (password == null) return false;
let meetsLengthRequirements = password.length >= minLength && password.length <= maxLength;
let hasUpperCaseLetter, hasLowerCaseLetter, hasDecimalDigit;
if (meetsLengthRequirements) {
for(let c of password) {
if (c.match(/[A-Z]/)) hasUpperCaseLetter = true;
if (c.match(/[a-z]/)) hasLowerCaseLetter = true;
if (c.match(/[0-9]/)) hasDecimalDigit = true;
}
}
return meetsLengthRequirements && hasUpperCaseLetter && hasLowerCaseLetter && hasDecimalDigit;
}