From the course: Mastering Nest.js: Build Scalable Applications with Mastery in Nest.js Framework

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Validating regex pattern

Validating regex pattern

To validate regex patterns in NestJS, the class validator offers a dedicated decorator called MatchesDecorator, which is commonly used for pattern-based validation. Let's see how it works. In the AuthDTO class, let's apply the pattern for the phone property. I'll remove the max length validator, and instead I will give matches decorator. It takes a regular expression pattern as an argument. So let me define the pattern. I'll give the caret sign and in square brackets, I'll give 0 to 9 to represent the character set. So in this case, it matches any single digit from 0 to 9. Then we need a range as well for the characters set as the numbers may be repeated. So in the curly braces, I'll give 10 comma 11 as range values. So the phone number has to be exactly 10 or 11 digits. I'll add the dollar sign to mark the end of the pattern. Let's also state a message. I'll give the message property and the message as phone number must be exactly 10 or 11 digits. Let's check the postman. I'll give…

Contents