---
description: A custom validation for the password.
---

# Regex pattern

As was said, a **regex** will be used to validate the password. Quoting [this article](https://en.wikipedia.org/wiki/Regular_expression) (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 <mark style="color:blue;">`password`</mark> 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.

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

> It was collected from [this answer](https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a/21456918#21456918) by **Srinivas** and edited by **Wiktor Stribiżew** (Stack Overflow).

{% hint style="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**)
{% endhint %}

{% hint style="info" %}
The site [regexr](https://regexr.com/) is great for learning about and experimenting with regexes.
{% endhint %}

What we should do now is to return to the <mark style="color:blue;">`CreateUserDto`</mark> file and add, over the <mark style="color:blue;">`password`</mark> field, the <mark style="color:blue;">`@Matches()`</mark> decorator. Inside it, use the aforementioned regex.

<mark style="color:green;">**Commit**</mark> - Validating password with regex
