Use validation groups for different schemas
developValidation groups allow you to apply different validation rules to the same class depending on the context (e.g., 'registration' vs 'admin').
- Assign groups to decorators using the
groupsoption:@Min(12, { groups: ['registration'] }). - Specify active groups in the
validatemethod:validate(user, { groups: ['registration'] }). - Use the
always: trueoption in a decorator to ensure that validation is applied regardless of which group is active.
Warning: If you provide a group combination that matches no decorators, it will result in an unknown value error.
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';
// Only validates 'age' (and it will fail because age is 10)
validate(user, { groups: ['registration'] });
// Only validates 'name' (and it will pass)
validate(user, { groups: ['admin'] });