Reputation: 148
I am creating some regex code so I can check passwords when a customer is trying to create a account. Currently I have two pieces of code that seem to work when tested on :- http://www.regexplanet.com/simple/index.html.
The first bit is:
^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$
This makes sure:
The second part is:
\S*(.)\1{3,}\S*
This makes sure:
Any 4 or more consecutive identical characters are matched.
The question is, how can I combine them both? I have tried to no avail but they seem to be working fine seperatly.
Thanks
Upvotes: 3
Views: 650
Reputation: 75222
If you simply combine that second regex to the first one, you'll be requiring all passwords to contain four consecutive, identical characters, and I'm pretty sure you want to forbid that. Try this:
^(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?:(.)(?!\1{3}))+$
The last group captures one character at a time, doing a negative lookahead each time to make sure it isn't followed by three more of the same character. Notice that I removed the .*
from the beginning of your first regex. That never belonged there, though it wasn't really hurting anything before. But in this regex the final group has to be the only part that consumes characters, or it doesn't do any good.
Upvotes: 1
Reputation: 6249
Why not just run two separate tests? The regex patterns above are complicated enough. Keeping them separate will make the code more understandable and will also give you the flexibility to add/remove additional tests without touching a pattern that is already working. Also, depending on which test fails, you can provide the user with a more detailed error message.
Upvotes: 0
Reputation: 2551
You might want to considering allowing passwords greater then at least 12 characters. Do yourself a favor and your customer's a favor and allow a customer to use any size password greater then 12 characters. Anything less then 12 is extremely easy to brute foce.
As to your question I will let somebody else answer that.
Upvotes: 1