简体   繁体   中英

Checking for uppercase/lowercase/numbers with Jquery

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.

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")
}

All of your regular expressions are searching for anything except the ranges that you have provided. So, [^AZ] looks for anything but 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?

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.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM