Dynamically set validation group with class-validator

Viewed 2290

Let's say I have a class like this

import {Min, Length, IsNotEmpty} from "class-validator";
 
export class User {
 
    @Max(10, {groups: ["child"]})
    @Max(100, {groups: ["adult"]})
    @Min(11, {groups: ["adult"]})
    age: number;
 
    @IsNotEmpty({groups: ["child", "adult"]})
    birthYear: number;

    @Length(2, 20, {groups: ["child", "adult"]})
    name: string;
}

I can validate this by doing

import { validate } from 'class-validator'
User user = new User()
user.age = 15
user.birthYear = 2005
user.name = 'name'
validate(user, groups: ["adult"])

What I'd like to do is dynamically set the group to use for validation based on the birthYear field. ValidateIf isn't something I want to use as there could be many fields and potentially complex conditionals.

It seems like I'll have to first validate the birthYear field to ensure that it meets the given validation requirements. This will require me to make a standalone class for birthYear purely for validation purposes as it seems there isn't a way to validate one field alone. If BirthYear then passes validation, I would use it to determine the validation group to use.

This feels like overkill and lots of work. Is there a way to add a validation group based on birthYear without having to validate birthYear beforehand, or validating it as a single field?

0 Answers
Related