Qwerty
Qwerty

Reputation: 75

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.

Upvotes: 0

Views: 31

Answers (1)

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4096

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 _, _, _';

Upvotes: 1

Related Questions