0
0
NestJSframework~30 mins

Custom validation decorators in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Validation Decorators in NestJS
📖 Scenario: You are building a NestJS backend for a user registration system. You want to ensure that the username field follows a custom rule: it must start with the letter 'A'. To do this, you will create a custom validation decorator.
🎯 Goal: Create a custom validation decorator called StartsWithA that checks if a string starts with the letter 'A'. Use this decorator in a DTO class to validate the username property.
📋 What You'll Learn
Create a custom validation decorator named StartsWithA using class-validator.
Create a DTO class called CreateUserDto with a username property.
Apply the StartsWithA decorator to the username property.
Use the IsString decorator from class-validator on username.
💡 Why This Matters
🌍 Real World
Custom validation decorators help enforce business rules on data inputs in backend APIs, improving data quality and user experience.
💼 Career
Backend developers often create custom validators to handle unique validation needs beyond built-in rules, making this skill valuable for NestJS and Node.js jobs.
Progress0 / 4 steps
1
Create the DTO class with username property
Create a class called CreateUserDto with a public property username of type string.
NestJS
Need a hint?

Define a class with a property named username of type string.

2
Add IsString decorator to username
Import IsString from class-validator and add the @IsString() decorator above the username property in CreateUserDto.
NestJS
Need a hint?

Use @IsString() decorator from class-validator on the username property.

3
Create the custom StartsWithA decorator
Import registerDecorator, ValidationOptions, and ValidationArguments from class-validator. Create a function called StartsWithA that takes an optional ValidationOptions parameter. Inside, use registerDecorator to define a validator that checks if the value starts with the letter 'A'.
NestJS
Need a hint?

Create a function that uses registerDecorator to check if the string starts with 'A'.

4
Apply the StartsWithA decorator to username
Add the @StartsWithA() decorator above the username property in CreateUserDto to enforce the custom validation rule.
NestJS
Need a hint?

Use the custom decorator @StartsWithA() on the username property.