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
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
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.