Search code examples
validationconditional-statementsnestjsoption-typeclass-validator

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 ?


Solution

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