NestJS course ยท Module 10: Data Validation

Custom Validators - Creating Your Own Guards

3 min read ยท
In this lesson5

The built-in class-validator decorators cover most cases. But what if you need a specialized guard that checks unique rules of your empire? It's time to learn how to create your own gate guards!

@ValidatorConstraint - full custom validator

The most flexible approach is to create your own validator class:

import {
  ValidatorConstraint,
  ValidatorConstraintInterface,
  ValidationArguments,
} from 'class-validator';

@ValidatorConstraint({ name: 'isRomanName', async: false })
export class IsRomanNameConstraint implements ValidatorConstraintInterface {
  validate(value: string, args: ValidationArguments): boolean {
    // Check if the name starts with an uppercase letter
    // and contains only Latin letters
    return /^[A-Z][a-z]+$/.test(value);
  }

  defaultMessage(args: ValidationArguments): string {
    return 'Name ($value) is not a valid Roman name!';
  }
}

The class must implement the ValidatorConstraintInterface with two methods:

  • validate() - returns true if the value is valid
  • defaultMessage() - returns the error message

Usage with @Validate()

import { Validate } from 'class-validator';

export class CreateLegionaryDto {
  @Validate(IsRomanNameConstraint)
  name: string;
}

Creating a Decorator - a cleaner approach

Instead of using @Validate(), you can create your own decorator:

import {
  registerDecorator,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from 'class-validator';

@ValidatorConstraint({ async: false })
class IsLegionCodeConstraint implements ValidatorConstraintInterface {
  validate(value: string): boolean {
    return /^LEG-[IVXLCDM]+-\d{3}$/.test(value);
  }

  defaultMessage(): string {
    return 'Legion code must have the format LEG-[Roman numerals]-[3 digits]';
  }
}

export function IsLegionCode(validationOptions?: ValidationOptions) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsLegionCodeConstraint,
    });
  };
}

Now you can use it like any other decorator:

export class CreateLegionaryDto {
  @IsLegionCode({ message: 'Invalid legion code!' })
  legionCode: string;
}

Asynchronous Validators

Sometimes validation requires database access (e.g., checking if a name is unique). In that case, you create an asynchronous validator:

@ValidatorConstraint({ name: 'isUniqueRank', async: true })
export class IsUniqueRankConstraint implements ValidatorConstraintInterface {
  constructor(private readonly legionService: LegionService) {}

  async validate(rank: string): Promise<boolean> {
    // Check in the database if the rank is available
    const existing = await this.legionService.findByRank(rank);
    return !existing;
  }

  defaultMessage(): string {
    return 'This rank is already taken in the legion!';
  }
}

Note: Asynchronous validators require integration with the NestJS Dependency Injection system through useContainer.

Cross-Field Validation

You can create validators that check relationships between fields:

@ValidatorConstraint({ async: false })
class IsAgeValidForRankConstraint implements ValidatorConstraintInterface {
  validate(value: any, args: ValidationArguments): boolean {
    const object = args.object as CreateLegionaryDto;
    // Legatus must be at least 30 years old
    if (object.rank === 'legatus' && object.age < 30) {
      return false;
    }
    // Centurio must be at least 25 years old
    if (object.rank === 'centurio' && object.age < 25) {
      return false;
    }
    return true;
  }

  defaultMessage(args: ValidationArguments): string {
    return 'Age does not meet the required rank!';
  }
}

With custom validators, you have full control over the validation logic. Your gate guards can now check any rules, even the most complex ones!

Code for this lesson: src/custom-validators.ts
// Custom Validators - Custom gate guards
import {
  ValidatorConstraint,
  ValidatorConstraintInterface,
  ValidationArguments,
  registerDecorator,
  ValidationOptions,
  Validate,
} from 'class-validator';

// TODO: Create custom validator IsRomanName
// Rule: name must start with a capital letter,
// contain at least 2 characters and only letters

@ValidatorConstraint({ name: 'isRomanName', async: false })
export class IsRomanNameConstraint
  implements ValidatorConstraintInterface
{
  validate(value: string, args: ValidationArguments): boolean {
    // TODO: Implement validation
    // Check: /^[A-Z][a-zA-Z]{1,}$/.test(value)
    return true; // Change to correct implementation
  }

  defaultMessage(args: ValidationArguments): string {
    return 'Name must be a valid Roman name!';
  }
}

// TODO: Create IsLegionCode decorator
// Format: LEG-[2-4 uppercase letters]-[3-4 digits]
export function IsLegionCode(options?: ValidationOptions) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName,
      options,
      validator: {
        validate(value: string): boolean {
          // TODO: Implement regex
          return /^LEG-[A-Z]{2,4}-\d{3,4}$/.test(value);
        },
        defaultMessage(): string {
          return 'Legion code must have format LEG-XX-000';
        },
      },
    });
  };
}

// Using custom validators
class CreateLegionaryDto {
  @Validate(IsRomanNameConstraint)
  name: string;

  @IsLegionCode()
  legionCode: string;
}

console.log('Custom validators created!');

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 methods must a class marked with @ValidatorConstraint implement?

  2. 2. How do you apply a custom validator created with @ValidatorConstraint to a DTO field?

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

Hands-on tasks in the game

  • Code editor

    Implement the validate method in IsLatinTextConstraint to check the regex /^[a-zA-Z .]+$/

  • Vertical ordering

    Arrange the elements for creating a custom validation decorator in the correct order:

  • Code editor

    Implement the AgeForRankConstraint logic: legatus min 35, centurio min 25, miles min 16

  • Code editor

    Implement the @IsRomanNumeral decorator using registerDecorator

  1. QuestionValidatorConstraintInterface
  2. QuestionUsing a Custom Validator
  3. Coding taskCustom Validator Implementation
  4. Put in orderregisterDecorator Structure
  5. Coding taskCross-field Validation
  6. QuestionAsynchronous Custom Validators
  7. Coding taskCreating a Custom Validation Decorator

Useful articles