-1

You can help me with this problem that I have, I would like to validate a password with specific requirements, which are: - It must contain a number, a capital letter and a special character. It must also be between 8 and 12 characters. Make the following pattern:

$special_chars = '!@#$%^&*()';
$pattern = "/[A-Z0-9{$special_chars}]{8,12}/";
$password = '$dsd%FG23X';
preg_match($pattern, $password, $matches);

But it does not work and I need to know what the correct pattern would be.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
dimacros
  • 47
  • 4

1 Answers1

1

Try using the positive look-ahead. I've used regex101 to build the expression. First we check the required characters, then we check for the length. Here's what I came up with:

$special_chars = '!@#$%^&*(),.`';
$pattern = '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[' . $special_chars . ']).*$/';

$password = '$dsd%FG23X';
preg_match($pattern, $password, $matches);

$password_validated = false;

if (strlen($password) >= 8 && strlen($password) < 50)
{
    if ( ! empty($matches)) {
        $password_validated = true;
    }
}

var_dump($password_validated);

Returns:

bool(true)

By the way, it's good to have a minimum password length, but it is a bad idea to have such a short maximum. You should allow the users the ability to have more complex characters, consider allowing something generous, like 50 characters. I generate my passwords with KeePass and they are usually at least 20 characters long.

Hope this helps!

mkveksas
  • 171
  • 8