Skip to content

Validation Messages

You can specify validation messages in the decorator options and that message will be returned in the ValidationError returned by the validate method (in the case that validation for this field fails).

Basic Usage

import { MinLength, MaxLength } from 'class-validator';

export class Post {
    @MinLength(10, {
        message: 'Title is too short',
    })
    @MaxLength(50, {
        message: 'Title is too long',
    })
    title: string;
}

Message Variables

There are few special tokens you can use in your messages:

  • $value - the value that is being validated
  • $property - name of the object's property being validated
  • $target - name of the object's class being validated
  • $constraint1, $constraint2, ... $constraintN - constraints defined by specific validation type

Example:

import { MinLength, MaxLength } from 'class-validator';

export class Post {
    @MinLength(10, {
        message: 'Title is too short. Minimal length is $constraint1 characters, but actual is $value',
    })
    @MaxLength(50, {
        message: 'Title is too long. Maximal length is $constraint1 characters, but actual is $value',
    })
    title: string;
}

Dynamic Messages

You can also provide a function that returns a message. This allows you to create more granular messages:

import { MinLength, ValidationArguments } from 'class-validator';

export class Post {
    @MinLength(10, {
        message: (args: ValidationArguments) => {
            if (args.value.length === 1) {
                return 'Too short, minimum length is 1 character';
            } else {
                return 'Too short, minimum length is ' + args.constraints[0] + ' characters';
            }
        },
    })
    title: string;
}

The message function accepts ValidationArguments which contains:

  • value - the value that is being validated
  • constraints - array of constraints defined by specific validation type
  • targetName - name of the object's class being validated
  • object - object that is being validated
  • property - name of the object's property being validated

Need documentation like this for your own product?

This site was built by Sonicar Tech LLC — we help SaaS, B2B, Enterprise, FinTech, and AI companies launch professional, docs-as-code documentation 60% faster and cheaper than building an in-house team, with first drafts delivered in 1 week.

Visit sonicar.tech