NestJS course Β· Module 10: Data Validation
Project - a complete validation system for the Empire
In this lesson8
The eight lessons of this module met the sentries one at a time: the class-validator decorators, ValidationPipe, transformations, nested validation, custom validators and groups. The project is where they all stand at one gate together - and then the thing that matters most turns out to be something no single lesson dwelt on: the order in which they run.
You will build a legion management system with full CRUD and validation of every input: DTOs for the legion, the legionary and the weapon, a custom validator, response transformations and a global gate configuration.
The order that explains the rest
Before you write a line, learn the road a request travels:
- It arrives as a plain JSON object - no classes, no types, everything a string or a number.
class-transformerturns it into an instance of the DTO class, running@Typeand@Transformon the way.class-validatorchecks the validation decorators on that instance.- Only then does the result reach the handler.
From which follows a conclusion that will save you an evening: transformation happens before validation. @Transform(({ value }) => value.trim()) cuts the spaces off first, and only then does @MinLength(2) count the characters - so " A " is rejected, though to the eye it holds five.
Step 1 - enums and the first DTO
// enums.ts
export enum LegionaryRank {
MILES = 'miles',
OPTIO = 'optio',
CENTURIO = 'centurio',
TRIBUNUS = 'tribunus',
LEGATUS = 'legatus',
}
export enum WeaponType {
GLADIUS = 'gladius',
PILUM = 'pilum',
SCUTUM = 'scutum',
PUGIO = 'pugio',
}
// weapon.dto.ts
export class CreateWeaponDto {
@IsString()
@IsNotEmpty()
name: string;
@IsEnum(WeaponType)
type: WeaponType;
@IsNumber()
@Min(1)
@Max(100)
damage: number;
}Note that the ranks and weapon types are enums, not unions such as 'miles' | 'optio'. The reason is the very one this library exists for: TypeScript types vanish at compilation. A union leaves nothing behind that a validator could question at run time; an enum remains an ordinary object, so @IsEnum(WeaponType) has something to compare against.
The @Min and @Max on damage are not ornament. Without them a client sends damage: -5 or damage: 999999 and the database accepts both without blinking.
Step 2 - nested validation
export class CreateLegionaryDto {
@IsString()
@IsNotEmpty()
@MinLength(2)
@MaxLength(50)
@Transform(({ value }) => value.trim())
name: string;
@IsEnum(LegionaryRank)
rank: LegionaryRank;
@IsNumber()
@Min(16)
@Max(65)
age: number;
@Matches(/^LEG-[A-Z]{2,4}-\d{4}$/, {
message: 'The ID must have the format LEG-XX-0000',
})
militaryId: string;
@IsArray()
@ArrayMinSize(1)
@IsString({ each: true })
skills: string[];
@ValidateNested()
@Type(() => CreateWeaponDto)
primaryWeapon: CreateWeaponDto;
@IsOptional()
@ValidateNested()
@Type(() => CreateWeaponDto)
secondaryWeapon?: CreateWeaponDto;
}Here lies the commonest trap in the whole module. @ValidateNested() without @Type() does not work - and it reports no error. Without @Type the transformer leaves a plain object in primaryWeapon rather than an instance of CreateWeaponDto; the validator looks inside, finds no decorators at all, and concludes that everything is in order. A weapon with negative damage passes the gate, because nobody posted a sentry there.
Two additions worth noticing. @IsString({ each: true }) checks every element of the array rather than the array as a whole - without each the rule would apply to the skills field itself. And @IsOptional() must stand before the other decorators of an optional field: it tells the validator to skip the remaining rules when the value is absent, instead of demanding it.
Step 3 - an array of nested objects
export class CreateLegionDto {
@IsString()
@IsNotEmpty()
@MinLength(3)
name: string;
@IsEnum(LegionStatus)
status: LegionStatus;
@IsNumber()
@Min(1000)
@Max(6000)
maxSoldiers: number;
@IsArray()
@ArrayMinSize(1)
@ValidateNested({ each: true })
@Type(() => CreateLegionaryDto)
soldiers: CreateLegionaryDto[];
}The difference from the previous step fits in two words: { each: true }. Without it @ValidateNested() would check the array as a single object - which in practice means nothing at all. With it every legionary is validated in full, separately, weapons included, because nesting works recursively: legion β legionary β weapon.
It is worth being aware of the cost. A legion of six thousand soldiers, each with two weapons, means tens of thousands of checks on one request. At those sizes you add @ArrayMaxSize and consider taking soldiers through a separate endpoint - validation is cheap, but it is not free.
Step 4 - a custom validator
@ValidatorConstraint({ async: false })
class IsValidMilitaryIdConstraint implements ValidatorConstraintInterface {
validate(value: string): boolean {
if (!value) return false;
const parts = value.split('-');
if (parts.length !== 3) return false;
if (parts[0] !== 'LEG') return false;
const numericPart = parseInt(parts[2], 10);
return numericPart > 0 && numericPart <= 9999;
}
defaultMessage(): string {
return 'Invalid military identifier';
}
}
export function IsValidMilitaryId(options?: ValidationOptions) {
return function (object: object, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName,
options,
validator: IsValidMilitaryIdConstraint,
});
};
}A custom validator always has two parts: the class holding the rule and the decorator function that registers it. The class supplies a validate returning a boolean and a defaultMessage with the wording; the function lets you use the rule exactly like a built-in one, through @IsValidMilitaryId().
Why bother, when @Matches from step two does something similar? Because a regular expression checks the shape, not the sense. Here a further condition appears - that the number falls between 1 and 9999 - a rule belonging to the domain rather than the syntax. As such conditions multiply, they all have one home, and the error message can be written in plain words. The { async: false } flag says the rule does not reach for the database; for a uniqueness check you set true and validate returns a Promise.
Step 5 - the response DTO
export class LegionaryResponseDto {
@Expose()
name: string;
@Expose()
rank: string;
@Expose()
@Transform(({ value }) => (value > 10 ? 'Veteranus' : 'Tiro'))
experienceLevel: string;
@Exclude()
secretMissionCode: string;
@Exclude()
salary: number;
}Validation watches what comes in. Here we watch what goes out - equally important, since a leak of pay and mission codes will not announce itself. @Expose() lets a field through, @Exclude() removes it, @Transform computes a derived value on the fly.
One thing is easy to forget: the decorators alone do nothing. For them to take effect the controller needs @UseInterceptors(ClassSerializerInterceptor), or you must call plainToInstance with excludeExtraneousValues: true. Without that the service returns a plain object and @Exclude() remains an annotation with no consequence - and that is exactly how data leaks that everybody believed was hidden.
Step 6 - configuring the gate
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: {
enableImplicitConversion: true,
},
}),
);
await app.listen(3000);
}Four options, four decisions. whitelist: true strips fields absent from the DTO. forbidNonWhitelisted: true goes further and rejects such a request with a 400 - the stricter choice, and by that token the more honest one: the client learns it sent something unexpected, instead of assuming you saved its field.
transform: true makes the handler receive an instance of the DTO class rather than a plain object - without it the @Type and @Transform of the earlier steps lie dead. enableImplicitConversion: true adds conversion of simple types: "25" from a query parameter becomes the number 25, because the field's type says number. Switch that last one on deliberately - it is convenient, but it can turn "0" into 0 and "false" into true.
What you hand in
The project is finished when it meets five conditions:
- CRUD for legions - endpoints for creating, reading, updating and deleting.
- DTOs with
class-validatorfor every input, with nested validation and arrays. - At least one custom validator registered through
registerDecorator. - Transformations with
class-transformeron the way in (@Type,@Transform) and on the way out (@Expose,@Exclude). - A global
ValidationPipewith the options from step six.
Check two things at the end, the two that most often slip by: that every @ValidateNested has a @Type beside it, and that the fields marked @Exclude() really do not appear in the response. Both fail quietly - no error, no warning, until the day somebody notices.
Send the link to your repository when you are done.
Code for this lesson: src/complete-validation.ts
// Main project - Complete Imperium Validation System
import {
IsString, IsNotEmpty, IsEnum, IsNumber,
Min, Max, MinLength, MaxLength, IsArray,
ArrayMinSize, ValidateNested, IsOptional, Matches,
ValidatorConstraint, ValidatorConstraintInterface,
registerDecorator, ValidationOptions,
} from 'class-validator';
import { Type, Transform, Exclude, Expose } from 'class-transformer';
// === ENUMS ===
enum LegionaryRank {
MILES = 'miles',
OPTIO = 'optio',
CENTURIO = 'centurio',
LEGATUS = 'legatus',
}
enum WeaponType {
GLADIUS = 'gladius',
PILUM = 'pilum',
SCUTUM = 'scutum',
}
// === CUSTOM VALIDATOR ===
// TODO: Implement IsValidMilitaryId
@ValidatorConstraint({ async: false })
class IsValidMilitaryIdConstraint
implements ValidatorConstraintInterface {
validate(value: string): boolean {
if (!value) return false;
return /^LEG-[A-Z]{2,4}-\d{4}$/.test(value);
}
defaultMessage(): string {
return 'Invalid military ID!';
}
}
// === WEAPON DTO ===
class CreateWeaponDto {
@IsString()
@IsNotEmpty()
name: string;
@IsEnum(WeaponType)
type: WeaponType;
@IsNumber()
@Min(1)
@Max(100)
damage: number;
}
// === LEGIONARY DTO ===
// TODO: Complete the missing decorators
class CreateLegionaryDto {
@IsString()
@IsNotEmpty()
@MinLength(2)
@Transform(({ value }) => value.trim())
name: string;
@IsEnum(LegionaryRank)
rank: LegionaryRank;
@IsNumber()
@Min(16)
@Max(65)
age: number;
// TODO: Add nested validation for weapon
@ValidateNested()
@Type(() => CreateWeaponDto)
weapon: CreateWeaponDto;
@IsArray()
@ArrayMinSize(1)
@IsString({ each: true })
skills: string[];
}
// === RESPONSE DTO ===
class LegionaryResponse {
@Expose()
name: string;
@Expose()
rank: string;
@Exclude()
salary: number;
}
console.log('Complete Imperium validation system ready!');
Docs entries used in this lesson
Spotted a mistake in this lesson?