gpt4 book ai didi

javascript - 如何在 JS 验证过程中区分特殊字符

转载 作者:行者123 更新时间:2023-12-01 03:09:46 24 4
gpt4 key购买 nike

我正在用 JS 编写一个密码验证器(非常基本,这只是一个练习),当我尝试验证大写或小写时,我会得到一个“有效密码”答案,即使没有一个或其他存在,只要有特殊字符在里面。我知道为什么会发生这种情况,但我想弄清楚的是如何在验证小写或大写时排除特殊字符。代码如下:

function ValidatePassword(input){
if(hasUppercase(input) && hasLowercase(input) && isLongEnough(input) && hasSpecialCharacters(input)){
console.log('The password is valid.');
}else if(!hasUppercase(input)){
console.log('The password needs at least one capital letter.');
}else if(!hasLowercase(input)){
console.log('The password needs at least one lowercase letter.');
}else if(!isLongEnough(input)){
console.log('The password needs to be at least 8 characters long.');
}else if(!hasSpecialCharacters(input)){
console.log('The password needs at least one special character.');
}
}

function hasUppercase(input){
for(var i = 0; i < input.length; i++){
if(input[i] === input[i].toUpperCase()){
return true;
}
}
}

function hasLowercase(input){
for (var i = 0; i < input.length; i++){
if(input[i] === input[i].toLowerCase()){
return true;
}
}
}

function isLongEnough(input){
if(input.length >= 8){
return true;
}
}

function hasSpecialCharacters(input){
var specialCharacters = ["/", "*", "-", "+", "_", "@", "%", "&", "<", ">", "!", "(", ")", "$", "^", "\\", "#", ".", ",", ";", ":"];
for(var i = 0; i < input.length; i++){
for(var j = 0; j < specialCharacters.length; j++){
if(input[i] === specialCharacters[j]){
return true;
}
}
}
}

无论如何,我很感激您能给我的任何帮助

最佳答案

如下所述更改 upperCase 和 lowerCase 函数

function hasLowercase(str) {
return (/[a-z]/.test(str));
}

function hasUppercase(str) {
return (/[A-Z]/.test(str));
}

关于javascript - 如何在 JS 验证过程中区分特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45927808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com