Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password validation regex

Tags:

syntax

regex

I am trying to get one regular expression that does the following:

  1. makes sure there are no white-space characters
  2. minimum length of 8
  3. makes sure there is at least:
    • one non-alpha character
    • one upper case character
    • one lower case character

I found this regular expression:

((?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])(?!\s).{8,})

which takes care of points 2 and 3 above, but how do I add the first requirement to the above regex expression?

I know I can do two expressions the one above and then

\s

but I'd like to have it all in one, I tried doing something like ?!\s but I couldn't get it to work. Any ideas?

like image 475
Jose Avatar asked Feb 21 '11 16:02

Jose


2 Answers

^(?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])\S{8,}$

should do. Be aware, though, that you're only validating ASCII letters. Is Ä not a letter for your requirements?

\S means "any character except whitespace", so by using this instead of the dot, and by anchoring the regex at the start and end of the string, we make sure that the string doesn't contain any whitespace.

I also removed the unnecessary parentheses around the entire expression.

like image 148
Tim Pietzcker Avatar answered Oct 26 '22 10:10

Tim Pietzcker


Tim's answer works well, and is a good reminder that there are many ways to solve the same problem with regexes, but you were on the right track to finding a solution yourself. If you had changed (?!\s) to (?!.*\s) and added the ^ and $ anchors to the end, it would work.

^((?=.*[^a-zA-Z])(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{8,})$
like image 42
EvilAmarant7x Avatar answered Oct 26 '22 10:10

EvilAmarant7x