Skip to content

Validation Groups

Overview

In different situations you may want to use different validation schemas for the same object. In such cases you can use validation groups.

Important

Calling a validation with a group combination that would not result in a validation (e.g. a non-existent group name) will result in an unknown value error. When validating with groups, the provided group combination should match at least one decorator.

Basic Usage

import { validate, Min, Length } from 'class-validator';

export class User {
    @Min(12, {
        groups: ['registration']
    })
    age: number;

    @Length(2, 20, {
        groups: ['registration', 'admin']
    })
    name: string;
}

let user = new User();
user.age = 10;
user.name = 'Alex';

validate(user, {
    groups: ['registration']
}); // this will not pass validation

validate(user, {
    groups: ['admin']
}); // this will pass validation

validate(user, {
    groups: ['registration', 'admin']
}); // this will not pass validation

validate(user, {
    groups: undefined // the default
}); // this will not pass validation since all properties get validated regardless of their groups

Important Notes

  • The always: true flag in validation options means the validation must be applied regardless of groups
  • Multiple groups can be specified for a single decorator
  • If no groups are specified, the default group is used
  • Groups can be used to create different validation scenarios for the same object

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