Reputation: 379
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
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
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
Reputation: 1
you can use Custom validation classes
,
Because nestjs uses it you can make it too.
Upvotes: 0