Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex strong password the special characters

Tags:

regex

php

I am currently making some tests with regex. I had an exercise which requested to check for a strong password, which means it should have: at least one number,one lowercase letter, one uppercase letter, no spaces, and at least one character that is not a letter or number. And it should be between 8-16 characters.

I wrote this code:

     <?php

  $passwords = array("Jtuhn", "12J@k", "jok", "Joan 12@45", "Jghf2@45", "Joan=?j123j");

  foreach($passwords as $pass)
  {
    ///^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$/
    if(strlen($pass) >= 8 && strlen($pass) < 17)
     {
       if(preg_match("/^\w*(?=\w*\d)(?=\w*[A-Z])(?=\w*[^0-9A-Za-z])(?=\w*[a-z])\w*$/", $pass) )
        echo "$pass => MATCH<br>";
       else
        echo "$pass => FAIL<br>";
     }
    else
      echo "$pass => FAIL(because of length)<br>";
  }
 ?>

The last two should match but they fail. I think the problem stands at

(?=\w*[^0-9A-Za-z])

which is supposed to be the pattern match to have at least one character that is not a letter or a number, but I cant figure out why. I know this strong password is solved in internet but thats not my issue. My issue is why that part of work dont do what is supposed to do.

like image 935
Joan Plepi Avatar asked Nov 28 '22 20:11

Joan Plepi


1 Answers

You could split your regex into different checks.

It will allow you to write more readable conditions and to display specific error messages. Although, regexp patterns will be easier to write and to understand.

i.e. :

$errors = array();
if (strlen($pass) < 8 || strlen($pass) > 16) {
    $errors[] = "Password should be min 8 characters and max 16 characters";
}
if (!preg_match("/\d/", $pass)) {
    $errors[] = "Password should contain at least one digit";
}
if (!preg_match("/[A-Z]/", $pass)) {
    $errors[] = "Password should contain at least one Capital Letter";
}
if (!preg_match("/[a-z]/", $pass)) {
    $errors[] = "Password should contain at least one small Letter";
}
if (!preg_match("/\W/", $pass)) {
    $errors[] = "Password should contain at least one special character";
}
if (preg_match("/\s/", $pass)) {
    $errors[] = "Password should not contain any white space";
}

if ($errors) {
    foreach ($errors as $error) {
        echo $error . "\n";
    }
    die();
} else {
    echo "$pass => MATCH\n";
}

Hope it helps.

like image 53
JazZ Avatar answered Nov 30 '22 10:11

JazZ