Reputation: 133
Let's say I have a DTO with a category property:
@ApiProperty()
@IsEnum(Category)
category: Category;
and then I have some other property
@ApiProperty()
@IsString()
@MaxLength(1000)
name: string
And what I want to do is change the max length number of name conditionally depending on what category is chosen - if it's "x" then it should be 500, if it's "y" then 700 etc. Is it something I could do easily?
Upvotes: 2
Views: 3094
Reputation: 470
You can have a work-around by using groups in ValidatorOptions
import { MaxLength, MinLength, IsString} from "class-validator";
export class User {
@MaxLength(500, {groups: ["x"]})
@MinLength(1000, {groups: ["y"]})
// or specify min,max length
// Length(2, 500, { groups: ["x"]})
// Length(2, 1000, { groups: ["y"]})
@IsString()
name: string;
}
And, when you instantiate an entity, you can specify a group like this.
User user = new User()
user.name = 'name'
validate(user, groups: ["x"])
Upvotes: 0