2

So before any one shuts this down, I am referencing an answer and asking a question here.

So the question I have is I want a strong password validation for laravel, something that includes 10 character, numbers, upper lower case, so on and so forth.

I found it: https://stackoverflow.com/a/31549892/1270259

The problem is, this regex looks off:

/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/

And since I am not good with regex I thought I would ask how can I fix it such that it validates:

  • Must be 10 characters long
  • Must contain upper and lower case
  • Must contain at least one number
  • Must contain at least one special character.

I feel like they were close in the answer. When this is run against github actions the error that comes back is preg_match(): Compilation failed: escape sequence is invalid in character class at offset 46.

Any thoughts as too how I can make this work for Laravel 7 to match the above constraints?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
TheWebs
  • 12,470
  • 30
  • 107
  • 211
  • Instead of having one regex for all your requirements why don't you validate against one requirement at a time. Not only will it simplify your regex to something understandable for you, it will also allow you to respond with a relevant message on failure because you'll know which part of the validation it failed. – Azeame Apr 12 '20 at 15:16
  • 2
    Having double checked the thread you linked, checkout the answer with 17 upvotes, that's exactly what I was referring to. – Azeame Apr 12 '20 at 15:20

1 Answers1

6

Use the principle of contrast:

^
(?=[^a-z]*[a-z]) # ensure one lower case letter
(?=[^A-Z]*[A-Z]) # ensure one upper case letter
(?=\D*\d)        # ensure a digit
(?=[^!@?]*[!@?]) # special chars
.{10,}           # at least 10 characters long
$

You can extend the special char section, of course.
See a demo on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79