0
0
NestJSframework~10 mins

Custom validation decorators in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom validation decorators
Define validation logic function
Create decorator using ValidatorConstraint
Apply decorator to DTO property
NestJS runs validation on DTO
Custom validator checks value
Allow request
This flow shows how you define a custom validator, create a decorator, apply it to data, and how NestJS uses it to accept or reject input.
Execution Sample
NestJS
import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';

@ValidatorConstraint({ async: false })
class IsEvenConstraint implements ValidatorConstraintInterface {
  validate(value: number) { return value % 2 === 0; }
}

export function IsEven(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsEvenConstraint,
    });
  };
}
Defines a custom decorator @IsEven that checks if a number is even.
Execution Table
StepActionInput ValueValidation ResultEffect
1Create IsEvenConstraint class--Validator logic ready
2Define @IsEven decorator--Decorator function ready
3Apply @IsEven to DTO property 'age'--Property marked for validation
4Validate DTO with age=44truePasses validation
5Validate DTO with age=55falseFails validation, error returned
6Validate DTO with age=00truePasses validation
7Validate DTO with age=-2-2truePasses validation
8Validate DTO with age=3.53.5falseFails validation, error returned
9Validation ends--Request accepted or rejected based on result
💡 Validation stops after checking the input value with the custom validator logic.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 6After Step 7After Step 8Final
value-450-23.5-
validationResult-truefalsetruetruefalse-
Key Moments - 3 Insights
Why does the validation fail for 3.5 even though it's a number?
The custom validator checks if the number is even using modulo (% 2 === 0). Since 3.5 % 2 is not zero, it fails. See execution_table row 8.
What happens if we forget to register the decorator with registerDecorator?
The validation will not run because NestJS won't know about the custom validator. The decorator must call registerDecorator as shown in execution_table step 2.
Can the validator handle negative even numbers?
Yes, negative even numbers like -2 pass because modulo works the same. See execution_table step 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5. What is the validation result for input value 5?
Atrue
Bfalse
Cundefined
Derror
💡 Hint
Check the 'Validation Result' column at step 5 in the execution_table.
At which step does the validation pass for the input value 0?
AStep 4
BStep 6
CStep 7
DStep 8
💡 Hint
Look for input value 0 in the 'Input Value' column and see its validation result.
If the validate method returned true for all numbers, how would the validation results change?
AAll inputs would pass validation
BOnly even numbers would pass
COnly odd numbers would pass
DValidation would always fail
💡 Hint
Consider what happens if validate always returns true regardless of input.
Concept Snapshot
Custom validation decorators in NestJS:
- Create a class implementing ValidatorConstraintInterface
- Define validate() with your logic
- Use @ValidatorConstraint() on the class
- Create a decorator function calling registerDecorator
- Apply decorator to DTO properties
- NestJS runs your validator during validation pipeline
Full Transcript
This example shows how to create a custom validation decorator in NestJS using class-validator. First, you define a class with a validate method that checks if a number is even. Then, you decorate this class with @ValidatorConstraint. Next, you create a decorator function that registers this validator with registerDecorator. When you apply this decorator to a DTO property, NestJS will run your custom validation logic during request validation. The execution table traces validation for different input values, showing which pass or fail. Key moments clarify common confusions like handling decimals or negative numbers. The visual quiz tests understanding of validation results at specific steps. This approach helps you add your own rules beyond built-in validators in NestJS.