Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this regular expression fail?

I have a password validation script in PHP that checks a few different regular expressions, and throws a unique error message depending on which one fails. Here is an array of the regular expressions and the error messages that are thrown if the match fails:

array(
    'rule1' => array(
        '/^.*[\d].*$/i',
        'Password must contain at least one number.'
    ),
    'rule2' => array(
        '/^.*[a-z].*$/i',
        'Password must contain at least one lowercase letter'
    ),
    'rule3' => array(
        '/^.*[A-Z].*$/i',
        'Password must contain at least one uppercase letter'
    ),
    'rule4' => array(
        '/^.*[~!@#$%^&*()_+=].*$/i',
        'Password must contain at least one special character [~!@#$%^&*()_+=]'
    )
);

For some reason, no matter what I pass through the validation, the "Special Characters" rule fails. I'm guessing it's a problem with the expression. If there's a better (or correct) way to write these expressions, I'm all ears!

like image 528
Stephen Avatar asked Aug 23 '26 23:08

Stephen


1 Answers

I can't see a problem with your special characters regular expression, but I can see a problem with the upper and lower case checks:

/^.*[A-Z].*$/i

The i at the end means PCRE_CASELESS, i.e. it will ignore case. You should omit the i.

like image 113
Mark Byers Avatar answered Aug 26 '26 14:08

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!