Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex for password validation

Tags:

regex

php

I not getting the desired effect from a script. I want the password to contain A-Z, a-z, 0-9, and special chars.

  • A-Z
  • a-z
  • 0-9 >= 2
  • special chars >= 2
  • string length >= 8

So I want to force the user to use at least 2 digits and at least 2 special chars. Ok my script works but forces me to use the digits or chars back to back. I don't want that. e.g. password testABC55$$ is valid - but i don't want that.

Instead I want test$ABC5#8 to be valid. So basically the digits/special char can be the same or diff -> but must be split up in the string.

PHP CODE:

$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number    = preg_match('#[0-9]#', $password);
$special   = preg_match('#[\W]{2,}#', $password); 
$length    = strlen($password) >= 8;

if(!$uppercase || !$lowercase || !$number || !$special || !$length) {
  $errorpw = 'Bad Password';
like image 469
MrPizzaFace Avatar asked Dec 13 '22 00:12

MrPizzaFace


1 Answers

Using "readable" format (it can be optimized to be shorter), as you are regex newbie >>

^(?=.{8})(?=.*[A-Z])(?=.*[a-z])(?=.*\d.*\d.*\d)(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])[-+%#a-zA-Z\d]+$

Add your special character set to last [...] in the above regex (I put there for now just -+%#).


Explanation:

^                              - beginning of line/string
(?=.{8})                       - positive lookahead to ensure we have at least 8 chars
(?=.*[A-Z])                    - ...to ensure we have at least one uppercase char
(?=.*[a-z])                    - ...to ensure we have at least one lowercase char
(?=.*\d.*\d.*\d                - ...to ensure we have at least three digits
(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d]) 
                               - ...to ensure we have at least three special chars
                                    (characters other than letters and numbers)
[-+%#a-zA-Z\d]+                - combination of allowed characters
$                              - end of line/string
like image 118
Ωmega Avatar answered Dec 28 '22 20:12

Ωmega