javascript 使用 Jquery 检查大写/小写/数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12763974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:03:46  来源:igfitidea点击:

Checking for uppercase/lowercase/numbers with Jquery

javascriptjqueryhtmlcss

提问by user1725794

Either I'm being really retarded here or its just the lack of sleep but why doesn't this work? If I use the "or" operator it works for each separate test but as soon as it change it to the "and" operator it stops working.

要么我在这里真的很迟钝,要么只是缺乏睡眠,但为什么这不起作用?如果我使用“或”运算符,它适用于每个单独的测试,但一旦将其更改为“和”运算符,它就会停止工作。

I'm trying to test the password input of a form to see if its contains lowercase, uppercase and at least 1 number of symbol. I'm having a lot of trouble with this so help would be lovely, here is the code I have.

我正在尝试测试表单的密码输入,以查看其是否包含小写、大写和至少 1 个符号。我在这方面遇到了很多麻烦,所以帮助会很可爱,这是我的代码。

var upperCase= new RegExp('[^A-Z]');
var lowerCase= new RegExp('[^a-z]');
var numbers = new RegExp('[^0-9]');

if(!$(this).val().match(upperCase) && !$(this).val().match(lowerCase) && !$(this).val().match(numbers))    
{
    $("#passwordErrorMsg").html("Your password must be between 6 and 20 characters. It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}
else
{
    $("#passwordErrorMsg").html("OK")
}

回答by cdn

All of your regular expressions are searching for anything exceptthe ranges that you have provided. So, [^A-Z] looks for anything but A-Z.

您所有的正则表达式都在搜索您提供的范围之外的任何内容。因此,[^AZ] 查找除 AZ 之外的任何内容。

You are also negating each match.

你也在否定每场比赛。

You might try modifying your regular expression definitions by removing the ^, and then reversing your logic. So,

您可以尝试通过删除 ^ 来修改正则表达式定义,然后反转逻辑。所以,

var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
var numbers = new RegExp('[0-9]');

if($(this).val().match(upperCase) && $(this).val().match(lowerCase) &&   $(this).val().match(numbers))  
{
    $("#passwordErrorMsg").html("OK")

}
else
{
    $("#passwordErrorMsg").html("Your password must be between 6 and 20 characters.     It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}

This might even be a bit more intuitive to read?

这甚至可能更直观一些?

回答by George SEDRA

var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
var numbers = new RegExp('[0-9]');

if($(this).val().match(upperCase) && $(this).val().match(lowerCase) &&   $(this).val().match(numbers) && $(this).val().lenght>=6 && $(this).val()<=20)  
{
    $("#passwordErrorMsg").html("OK")

}
else
{
    $("#passwordErrorMsg").html("Your password must be between 6 and 20 characters.     It must contain a mixture of upper and lower case letters, and at least one number or symbol.");
}