kaboom
kaboom

Reputation: 9

REGEX password validation without special characters

I am using this regex to validate my password. My password -

My regex is

^.*(?=.{8,})(?=.*\d*\d)(?=.*[a-zA-Z]*[a-zA-Z])(?!.*\W).*$

but unfortunately it still matches if I try to put special characters at the beginning. For example @password12, !password12.

Upvotes: 0

Views: 4135

Answers (3)

Tony
Tony

Reputation: 81

I had a similar situation in which the client needed 4 alpha, 1 number, and between 8 and 20 characters. I've adapted my solution to your problem:

^(?=(?:[a-zA-Z0-9]*[a-zA-Z]){2})(?=(?:[a-zA-Z0-9]*\d){2})[a-zA-Z0-9]{8,}$

I understand the other answers dissuading you from this route, but sometimes the client wants what the client wants, regardless of your arguments to the contrary.

Upvotes: 2

codaddict
codaddict

Reputation: 455282

You can use the following regex in case insensitive mode:

^(?=[a-z]*[0-9][a-z]*[0-9])^(?=[0-9]*[a-z][0-9]*[a-z])[a-z0-9]{8,}$

See it

Upvotes: 2

Bryan Oakley
Bryan Oakley

Reputation: 386210

Because your pattern begins and ends with .*, it will match anything at the beginning or end of the string, including special characters.

You shouldn't be solving this problem with a single regular expression, it makes the code hard to read and hard to modify. Write one function for each rule using whatever makes sense for that rule, then your validation script becomes crystal clear:

if is_alpha_only(password) && 
   len(password) > = 8 && 
   has_2_or_more_numbers(password) &&
   has_2_or_more_alpha(password) ...

Seriously, what's the point of cramming all of that into a single regular expression?

And why disallow special characters? There's simply no reason for that.

Upvotes: 2

Related Questions