ss_millionaire
ss_millionaire

Reputation: 429

Regular expression to match minimum password requirements and other characters

I want users signing up on my site to choose passwords that include:

But it doesn't match other characters asides those in the requirements listed above. I want to be able match a password that can contain any character but still meet the conditions above. How do i do this?

Upvotes: 2

Views: 1808

Answers (3)

Andy Lester
Andy Lester

Reputation: 93725

Don't do it all in one regex. It is far more readable and maintainable to make each validation its own check.

$passes =
    preg_match( '/[A-Z]/', $pw ) && # uppercase char
    preg_match( '/[a-z]/', $pw ) && # lowercase char
    preg_match( '/\d/', $pw ) &&    # digit
    (strlen($pw) > 8);              # at least 8 characters

Upvotes: 2

elixenide
elixenide

Reputation: 44841

This will do what you want:

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

Demo on regex101

Debuggex Demo

Explanation:

Regular expression visualization

  • ^ matches the start of the string
  • (?=.*[A-Z]) requires an uppercase character
  • (?=.*[a-z]) requires a lowercase character
  • (?=.*\d) requires a digit
  • .{8,} requires minimum length of 8.

Note: Unlike anubhava's answer, this allows for whitespace characters. If you don't want whitespace, use \S as suggested by anubhava.

Edit: Per the excellent point by @ridgerunner in the comments, here is a slightly more efficient regex:

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

This version avoids the lazy .* expression, which wastes time in testing the overall regex in this context.

Upvotes: 2

anubhava
anubhava

Reputation: 785491

Use this regex:

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

I have used \S (any non space character) instead of \w (word character that means [a-zA-Z0-9_])

Upvotes: 1

Related Questions