Search code examples
phpregexvalidationpasswordswhitelist

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.)


Solution

  • 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.