user1178560
user1178560

Reputation: 313

PHP -> REGEX | password validation not working

I use this (almost) complex password verification:

function is_password($password) {
    return preg_match("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$", $password);
}

So it must contain:

This does not seem to work. Whenever I type certain characters like e, t, o, j, c and b; the function returns true if allowed length is correct. So uppercase and digit is not being validated..

What am I doing wrong?

Upvotes: 3

Views: 1778

Answers (2)

Jocelyn
Jocelyn

Reputation: 11393

You forgot to use delimiters. Use this code instead:

return preg_match("/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/", $password);

Or you may split each condition and use this code:

return mb_strlen($password)>=6 && mb_strlen($password)<=20
       && preg_match("/[a-z]+/", $password) && preg_match("/[A-Z]+/", $password)
       && preg_match("/[0-9]+/", $password);

Upvotes: 7

Mark Hensler
Mark Hensler

Reputation: 61

I would break this apart into multiple checks. This will allow you to intelligently give feedback to the user (or to a log) as to why the password selection failed.

<?php
function is_password($password){
    if (strlen($password) < 6) {
        // too short
        return false;
    }
    if (strlen($password) > 20) {
        // too long
        return false;
    }
    if (!preg_match("/[A-Z]/", $password) {
        // no upper
        return false;
    }
    if (!preg_match("/[a-z]/", $password) {
        // no lower
        return false;
    }
    if (!preg_match("/[0-9]/", $password) {
        // no digit
        return false;
    }
    return true;
}
?>

Upvotes: 6

Related Questions