2

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?

1 Answer 1

0

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"])
Sign up to request clarification or add additional context in comments.

1 Comment

In NestJS he is not calling the validate manually, so this solution won't be useful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.