Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow underscore in this 'Password Complexity' regex

Tags:

regex

Here it is:

/(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/

It only passes if the password contains upper case AND lower case letters, and also either 1 digit or 1 special character, however I want underscore _ to count as a special character as well and it currently does not, how can modify this regex so that it will allow underscore to count as a special character?

EDIT: here is the context...

jQuery.validator.addMethod("complexity", function(value, element) {
    return this.optional(element) || /(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/.test(value);
}, "password is not complex, see requirements above");
like image 654
MetaGuru Avatar asked Nov 28 '22 00:11

MetaGuru


1 Answers

/(?=^.{8,}$)((?=.*\d)|(?=.*[\W_]+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/

aioobe was close replace \W with [\W_]

Just so you know this considers a space a special character.

Also I don't see where you are checking for numbers. EDIT: nevermind I found it. (man complex regexes are like a wheres waldo.)

Here is a simplifed version that does not allow spaces (and it is easyier to maintain)

(?=^.{8,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])(?=^.*[^\s].*$).*$
^          ^          ^          ^            ^
|          |          |          |            L--does not contain a whitespace
|          |          |          L--at least one non word character(a-zA-Z0-9_) or _ or 0-9
|          |          L--at least one upper case letter
|          L--at least one lowercase Letter
L--Number of charaters

These are your building blocks

(?=.*[a-z]) // Whatever is inside the [] meens the string contains at least one charter inside that set.
            // If you wanted a minimum of three lowercase letters you can chain the inner block like so 
               (?=(.*[a-z]){3,})
like image 196
Scott Chamberlain Avatar answered Dec 28 '22 15:12

Scott Chamberlain