typescript
61 lines · 10 steps
A custom validation pipe in NestJS
A NestJS pipe that strips undefined values before transforming and validating incoming DTOs.
Explained by
highlit
1import {
2 Injectable,
3 PipeTransform,
4 ArgumentMetadata,
5 BadRequestException,
6} from '@nestjs/common';
7import { plainToInstance } from 'class-transformer';
8import { validate } from 'class-validator';
9
10@Injectable()
11export class StripUndefinedValidationPipe implements PipeTransform {
12 async transform(value: unknown, { metatype }: ArgumentMetadata) {
13 if (!metatype || !this.shouldValidate(metatype)) {
14 return value;
15 }
16
17 const pruned = this.stripUndefined(value);
18 const instance = plainToInstance(metatype, pruned, {
19 exposeUnsetFields: false,
20 });
21
22 const errors = await validate(instance as object, {
23 whitelist: true,
24 forbidNonWhitelisted: true,
25 skipMissingProperties: true,
26 });
27
28 if (errors.length > 0) {
29 throw new BadRequestException(
30 errors.flatMap((e) => Object.values(e.constraints ?? {})),
31 );
32 }
33
34 return instance;
35 }
36
37 private shouldValidate(metatype: Function): boolean {
38 const primitives: Function[] = [String, Boolean, Number, Array, Object];
39 return !primitives.includes(metatype);
40 }
41
42 private stripUndefined(input: unknown): unknown {
43 if (Array.isArray(input)) {
44 return input.map((item) => this.stripUndefined(item));
45 }
46
47 if (input !== null && typeof input === 'object') {
48 return Object.entries(input as Record<string, unknown>).reduce(
49 (acc, [key, val]) => {
50 if (val !== undefined) {
51 acc[key] = this.stripUndefined(val);
52 }
53 return acc;
54 },
55 {} as Record<string, unknown>,
56 );
57 }
58
59 return input;
60 }
61}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing PipeTransform lets you inject custom sanitization logic into NestJS's request lifecycle before controllers run.
- 2Pruning undefined keys before validation keeps whitelist rules from misfiring on properties that were never really sent.
- 3Recursion handles nested objects and arrays uniformly so the same cleaning rule applies at every depth.
Related explainers
ruby
module CreditCard module_function def valid?(number)
Validating credit card numbers with Luhn
checksum
luhn-algorithm
validation
Intermediate
6 steps
go
package handlers type ListFilters struct { Status string `form:"status" binding:"omitempty,oneof=active archived all"`
Cross-field query validation in Gin
validation
struct-tags
query-binding
Intermediate
9 steps
typescript
import { CallHandler, ExecutionContext, Injectable,
Recording HTTP metrics with a NestJS interceptor
interceptor
observability
prometheus
Intermediate
5 steps
typescript
import { Component, inject, effect } from '@angular/core'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { toSignal } from '@angular/core/rxjs-interop';
Debounced search that syncs to the URL in Angular
signals
reactive-forms
debouncing
Advanced
8 steps
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-custom-validation-pipe-in-nestjs-explained-typescript-9880/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.