phpregexvalidationalphanumericpassword-strength

Deem password invalid if it contains N number of consecutive ascending alphanumeric characters


I have a specification to not allow users to create passwords with a certain number of incremented letters or numbers such as: abc, xyz, hij, 678, 789, or RST.

I have found regex match patterns which will match aaa or 777, but not ascending sequences.

How can I match these kinds of sequences?


Solution

  • You could use something like this:

    function inSequence($string, $num = 4) {
        $i = 0;
        $j = strlen($string);
        $str = implode('', array_map(function($m) use (&$i, &$j) {
            return chr((ord($m[0]) + $j--) % 256) . chr((ord($m[0]) + $i++) % 256);
        }, str_split($string, 1)));
        return preg_match('#(.)(.\1){' . ($num - 1) . '}#', $str);
    }