Regex pattern

A custom validation for the password.

As was said, a regex will be used to validate the password. Quoting this article:

A regular expression is a sequence of characters that specifies a match pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.

So in short, a regex may help us to identify patterns in a text. It would be interesting if the password would follow patterns such as

  • 8-20 characters

  • At least one

    • Uppercase letter

    • Lowercase letter

    • Number

    • Special character

We can use the following regex to achieve this result. It was collected from this answer.

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

Even though it may seem confusing at first, you can notice some patterns there, such as

  • There must be at least one of those desired characters (a-z | A-Z | \d | @$!%*?&)

  • Only they must be present, and nothing else (a-zA-Z\d@$!%*?&)

  • The character amount (8,20)

This site is great for learning about and experimenting with regexes.

What we should do now then is return to the CreateUserDto file and add, over the password field, the @Matches() decorator. Inside it, use the aforementioned regex.

Commit - Validating password with regex

Last updated