Marumba
Marumba

Reputation: 379

Is there a way to conditionally validate with class-validator?

I'm building a CRUD for users using Nest.js
I'd like to have the POST and PATCH receive the same DTO but have some fields optional in PATCH but mandatory in POST.

I couldn't find a way to do this other than keep all properties @IsOptional and manually write the validation in the code for POST requests.

Is there a better way to do it with class-validator ?

Upvotes: 1

Views: 6574

Answers (3)

ron
ron

Reputation: 826

You can try @ValidateIf conditional validation

If ValidateIf return true then the other validation will run

examle : in this case if o.otherProperty === 'value' then the @IsNotEmpty will run otherwise it will not run

export class Post {
  otherProperty: string;

  @ValidateIf(o => o.otherProperty === 'value')
  @IsNotEmpty()
  example: string;
}

Upvotes: 3

Ayoub Touba
Ayoub Touba

Reputation: 2987

NestJS Provides a beautiful solution for your problem,

you can use PartialType, To create a type with the same fields, but with each one optional, use PartialType() passing the class reference (PsotDto) as an argument:

export class PatchDto extends PartialType(PostDto) {}

Upvotes: 2

Cheolmin  Choi
Cheolmin Choi

Reputation: 1

you can use Custom validation classes, Because nestjs uses it you can make it too.

Upvotes: 0

Related Questions