Php regex password check

I am new to regex. I need to check passwords using php with the following password policy using Regex:

Passwords:

  • Must be at least 8 characters
  • Must be 2 numbers
  • Allowed characters ! @ # $ % * ! @ # $ % *

I tried the following: /^(?=.*\d)(?=.*[A-Za-z])[ 0-9A-Za-z!@ #$%]$/

+4
source share
3 answers

The following matches match your requirements: ^(?=.*\d.*\d)[ 0-9A-Za-z!@ #$%*]{8,}$

Online Demo <<< You don't need the modifiers, they are just there for testing purposes.

Explanation

  • ^ : start of line match
  • (?=.*\d.*\d) : positive view, check if there are 2 digits
  • [ 0-9A-Za-z!@ #$%*]{8,} : match numbers, letters, and !@ #$%* 8 or more times
  • $ : end of line end
+7
source

First, I would try to find two numbers using non-regex (or preg_match_all('[0-9]', ...) >= 2 , and then checking for:

^[ !@ #$%*a-zA-Z0-9]{8,}$

It should be faster and more understandable. To do this using only regular expression sounds, you need a lookahead that basically scans the expression twice afaik, although I am not sure about the internal functions of PHP on this.

Be prepared for many complaints that passwords are not accepted. I personally have a large subset of passwords that do not confirm these restrictions. Also meaningless passwords, such as 12345678 , will check or even 11111111 , but not f4# f@faASvCXZr $%%zcorrecthorsebatterystaple .

0
source
 if(preg_match('/[ !@ #$%*a-zA-Z0-9]{8,}/',$password) && preg_match_all('/[0-9]/',$password) >= 2) { // do } 
0
source

Source: https://habr.com/ru/post/1496451/


All Articles