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

Time:06-21

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 ?

CodePudding user response:

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) {}

CodePudding user response:

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

  • Related