How to create regex for passwords contain at least 1 of the following: lowercase letters, uppercase letters, numbers [duplicate]

StackOverflow https://stackoverflow.com/questions/23685093

  •  23-07-2023
  •  | 
  •  

Question

I'm trying to create a regex for my password validation in PHP. What I want is not at least 2 of both lowercase letter, uppercase letter, number and symbols, but at least one category from these three categories, for example, "Rose" would work, "Rose456" would also work, and "rose456" will work, "Rose456!" will also work.

Thank you so much!

Was it helpful?

Solution

It is much simpler to separately validate individual password requirements than to create a single uber-expression to validate everything all at once.

if(
  // mandatory matches
  strlen($password) > $minlength   &&     // enforce length
  preg_match('/[a-z]/', $password) &&     // contains lowercase
  preg_match('/[A-Z]/', $password)        // contains uppercase
) {
    $passed_count = 0;
    if( preg_match('/[0-9]/', $password) ) { $passed_count++; }  // contains digit
    if( preg_match('/[^a-zA-Z0-9]/', $password) ) { $passed_count++; }  // contains symbol
    if( $passed_count > $min_passed ) {
        // valid password
    }
}

edited to illustrate mandatory/optional checks

OTHER TIPS

So... you want either a lowercase letter, or an uppercase letter, or a number? In that case, /[a-zA-Z0-9]/ would suffice. You could even do /\w/ if you include underscores as well. But I can't really see how you're planning to use this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top