Qwerty Qwerty - 3 years ago 182
Javascript Question

PHP regex code for "does not match once"

Working on code similar to this previous post but for passwords ($email is now $password). Trying have validation check to see if password field has at least one number, one lowercase letter, one uppercase letter, and one of the symbols !@#$%^&*

PHP-side validation uses regex

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{6,20}$/


which works fine. However for js validation I'm using this for "if password does not contain one of each"

if (preg_match('/([^a-z]{1})([^A-Z]{1})(^\d{1})([^!@#$%^&*]{1})+/', $password, $matches)) {
echo 'Password must contain _, _, _';


Total beginner and very confused.

Answer Source

Why don't you use the same regex pattern in js too??

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{6,20}$/

This would work fine in js as well. If only you need to see if password does not contain one of each use a negation as

if (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{6,20}$/', $password, $matches)) {
echo 'Password must contain _, _, _';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download