drewwyatt
drewwyatt

Reputation: 6027

Validate password with minimum length and whitelisted characters

I want to require an 8 character password that allows upper and lowercase letters, numbers and !@#$%^&*-_ characters. Here is what I have that doesn't appear to be working:

preg_match('([A-za-z0-9-_!@#$%^&*]{8,})', $password)

Am I missing something really obvious?

Update: Yes, I was missing something really obvious - the open bracket [. However it still returns true when I use characters like a single quote or bracket. (Which are what I am trying to avoid.)

Upvotes: 0

Views: 386

Answers (2)

Mercurybullet
Mercurybullet

Reputation: 889

This may be easier to break into individual rules. I.e. a rule to check if the password is at least 8 characters long, another to check for an uppercase, another for lowercase, etc.

Also, it looks like you have some special characters in terms of regular expressions without any escaping. For example, the * character has special meaning in regular expressions other than some special cases. It either needs to be escaped \* or in brackets [*]

Upvotes: 0

mario
mario

Reputation: 145482

Basically you miss an opening [ character group bracket here:

              ↓
 preg_match('([A-za-z0-9-_!@#$%^&*()]{8,})', $password)

And you should also use delimiters. The parens will behave as such, but it's better to use a different pair to avoid ambiguity with a capture group:

 preg_match('/^([A-za-z0-9-_!@#$%^&*()]{8,})$/', $password)

This also adds start ^ and end $ assertions to match the whole string.

Upvotes: 2

Related Questions