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

문제

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!

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top