Regex pattern

A custom validation for the password.

As was said, a regex will be used to validate the password. Quoting this articlearrow-up-right (Wikipedia):

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.

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

It was collected from this answerarrow-up-right by Srinivas and edited by Wiktor Stribiżew (Stack Overflow).

circle-info

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)

circle-info

The site regexrarrow-up-right is great for learning about and experimenting with regexes.

What we should do now is to 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