Reputation: 2513
I tried and could not find an answer for this issue, so I'm asking this question.
I need to create a regex for password validation and it must have following conditions.
I have created following regex but it does not work properly.
preg_match('/[A-Za-z\d$!^(){}?\[\]<>~%@#&*+=_-]{8,40}$/', $newpassword)
Can somebody please help me to fix this regex properly?
Thanks.
Upvotes: 2
Views: 4642
Reputation: 4874
Here you go, using lookaheads to verify your conditions:
^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!^(){}<>%@#&*+=_-])[^\s$`,.\/\\;:'"|]{8,40}$
Let's break it down a little, because it's kinda nasty-looking:
^
asserts that it's at the start of the string.(?=.*[a-zA-Z])
, verifies that it contains at least one letter (upper or lower).(?=.*\d)
, verifies that it contains at least one digit.(?=.*[~!^(){}<>%@#&*+=_-])
, verifies that it contains at least one character from your special characters list.[^\s$,.\/\\;:'"|]{8,40}$
verifies that the entire string is between 8 and 40 characters long, and contains no spaces or illegal characters by using an inverted character class.Upvotes: 5