I working on NestJS app and trying to validate some field depending on other field.
export class CreateOrderDTO {
@IsDeliveryCodeValid() // Custom validator
delivery_code: string;
@IsAddressRequired() // Custom validator
@IsNotEmptyObject()
@ValidateNested()
@Type(() => CreateOrderAddressDTO)
address: CreateOrderAddressDTO;
}
In this code, delivery_code
is unique id of DeliveryType
which has needAddress
boolean field. I want to validate address only if this needAddress
field is set to true.
What I’m trying to achieve is create some custom decorator which checks if provided delivery_code
is code of one of delivery types and if found delivery type has needAddress
field set to true, if so we have to validate address
, otherwise we can ignore validators.
My ideas:
- It could be done in controller but I really want to check this at CreateOrderDTO level.
- Somehow transform whole DTO before validators run and add field
needAddress
to it’s body so validators can access it. - Manually transform DTO at
@IsDeliveryCodeValid()
decorator and add fieldneedAddress
to DTO body. It’s not really elegant way because I dont think i should transform dto in validators, it’s not their purpose and can be confusing.
Normally i would use @ValidateIf() but it doesnt accept async functions, so i can’t use a DB query here.
Thanks for your help!