Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using preg_match to identify a strong password [duplicate]

Tags:

html

regex

php

I had thought to use preg_match() to check if a password is correctly entered. I want at least 1 uppercase letter, at least 1 lowercase letter, at least one number, and at least one special char. Here's what I am using:

$pattern = "(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$";

This regex is working fine in HTML's "pattern" field. But I need to ensure that it's also verified for older browsers.

My PHP code is this:

if (!(preg_match($pattern, $loginpassword))) {echo "Password must include one uppercase letter, one lowercase letter, one number, and one special character such as $ or %."; die;}

I thought it was working great except when I use the password 1@abcdeF it also fails to match. The php code seems to work but no password ever matches, even when it SHOULD fit the pattern. HTML5 will let it through so I suspect the regex statement is correct, but something about my setup in PHP is flawed. Can anyone see what I'm missing?

like image 462
user1149499 Avatar asked Dec 20 '25 02:12

user1149499


1 Answers

Use the following pattern:

$strong_password = preg_match('/^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[^A-Za-z\d])[\s\S]{6,16}$/', $string);

^                 --> start of string

(?=.*[a-z])       --> at least one lowercase letter 

(?=.*[A-Z])       --> at least one uppercase letter 

(?=.*\d)          --> at least one number 

(?=.*[^A-Za-z\d]) --> at least one special character

[\s\S]{6,16}      --> total length between 6 and 16

$                 --> end of string
like image 119
Sibin John Mattappallil Avatar answered Dec 22 '25 15:12

Sibin John Mattappallil



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!