NestJS course ยท Module 10: Data Validation

Advanced Validation Decorators

3 min read ยท
In this lesson6

You already know the basic gate guards quite well. Now it's time to meet the elite guardsmen - advanced class-validator decorators that handle more complex situations.

@IsOptional() - the optional value guard

Not every field needs to be required. The @IsOptional() decorator says: "If this field exists, check it. If it doesn't exist - let it pass":

import { IsOptional, IsString, IsNumber } from 'class-validator';

export class UpdateLegionaryDto {
  @IsOptional()
  @IsString()
  nickname?: string;  // May not have a nickname

  @IsOptional()
  @IsNumber()
  bonusPay?: number;  // Bonus pay is optional
}

@IsEnum() - the allowed values guard

When a field can only accept specific values, we use @IsEnum(). It's like a list of allowed ranks in the legion:

import { IsEnum } from 'class-validator';

enum LegionaryRank {
  MILES = 'miles',
  OPTIO = 'optio',
  CENTURIO = 'centurio',
  LEGATUS = 'legatus',
}

export class CreateLegionaryDto {
  @IsEnum(LegionaryRank)
  rank: LegionaryRank;
  // 'centurio', 'imperator'
}

@IsArray() and @ArrayMinSize() - the array guards

When you expect an array of data, you need special guards:

import { IsArray, ArrayMinSize, IsString } from 'class-validator';

export class CreateLegioDto {
  @IsArray()
  @ArrayMinSize(1)
  @IsString({ each: true })
  skills: string[];
  // ["combat", "march"], [], "combat"
}

Note the { each: true } - this parameter tells the @IsString() decorator to check each element of the array, not the array itself.

@IsDateString() - the date guard

Verifies whether the value is a valid date string in ISO 8601 format:

import { IsDateString } from 'class-validator';

export class CreateEventDto {
  @IsDateString()
  enlistmentDate: string;
  // "2024-03-15T10:00:00Z", "yesterday"
}

@Matches() - the pattern guard (regex)

The most universal guard - checks whether the value matches a regular expression:

import { Matches, IsString } from 'class-validator';

export class CreateLegionaryDto {
  @IsString()
  @Matches(/^LEG-[A-Z]{3}-\d{4}$/, {
    message: 'Military ID must have the format LEG-XXX-0000',
  })
  militaryId: string;
  // "LEG-ROM-0042", "123ABC"
}

Full Example - Legion Recruitment Form

Let's combine all the advanced decorators in a complete DTO:

import {
  IsString,
  IsNotEmpty,
  IsEnum,
  IsOptional,
  IsArray,
  ArrayMinSize,
  IsDateString,
  Matches,
  IsNumber,
  Min,
  Max,
  MinLength,
} from 'class-validator';

enum LegionaryRank {
  MILES = 'miles',
  OPTIO = 'optio',
  CENTURIO = 'centurio',
  LEGATUS = 'legatus',
}

export class RecruitLegionaryDto {
  @IsString()
  @IsNotEmpty()
  @MinLength(2)
  name: string;

  @IsEnum(LegionaryRank)
  rank: LegionaryRank;

  @IsNumber()
  @Min(16)
  @Max(65)
  age: number;

  @IsDateString()
  enlistmentDate: string;

  @Matches(/^LEG-[A-Z]{3}-\d{4}$/)
  militaryId: string;

  @IsArray()
  @ArrayMinSize(1)
  @IsString({ each: true })
  skills: string[];

  @IsOptional()
  @IsString()
  nickname?: string;
}

With these decorators in your arsenal, you can validate virtually any data. Your API's gate guards are now well trained!

Code for this lesson: src/advanced-decorators.ts
// Advanced validation decorators
import {
  IsString,
  IsNotEmpty,
  IsEnum,
  IsOptional,
  IsArray,
  ArrayMinSize,
  IsDateString,
  Matches,
  IsNumber,
  Min,
} from 'class-validator';

// Legionary rank enums
enum LegionaryRank {
  MILES = 'miles',
  OPTIO = 'optio',
  CENTURIO = 'centurio',
  LEGATUS = 'legatus',
}

// TODO: Complete the DTO with advanced decorators
export class RecruitLegionaryDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  // TODO: Add @IsEnum with LegionaryRank
  rank: LegionaryRank;

  @IsNumber()
  @Min(16)
  age: number;

  // TODO: Add @IsDateString()
  enlistmentDate: string;

  // TODO: Add @Matches with regex /^LEG-[A-Z]{3}-\d{4}$/
  militaryId: string;

  // TODO: Add @IsArray, @ArrayMinSize(1), @IsString({ each: true })
  skills: string[];

  // TODO: Add @IsOptional() and @IsString()
  nickname?: string;
}

console.log('Advanced decorators ready!');

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the @IsOptional() decorator in class-validator do?

  2. 2. What is the @IsEnum() decorator used for in class-validator?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Complete the ProvinceType enum and add validation decorators to CreateProvinceDto

  • Vertical ordering

    Arrange the decorators from least to most restrictive:

  • Code editor

    Complete the @Matches and @IsDateString decorators in CreateDocumentDto

  • Click in order

    Arrange the elements of the @Matches decorator in the correct order:

  1. Question@IsOptional Decorator
  2. Question@IsEnum Decorator
  3. Coding taskEnums and Arrays in Validation
  4. Put in orderValidation Decorator Restrictiveness
  5. QuestionThe each Parameter in Decorators
  6. Coding taskValidation with Regular Expressions
  7. Click in orderBuilding the @Matches Decorator

Useful articles