Nestjs and Class Validator - at least one field should not be empty

5k views Asked by At

I have NestJS API, which has a PATCH endpoint for modifying a resource. I use the class-validator library for validating the payload. In the DTO, all fields are set to optional with the @IsOptional()decorator. Because of that, if I send an empty payload, the validation goes through and then the update operation errors.

I am wondering if there is a simple way to have all fields set to optional as I do and at the same time make sure that at least one of them is not empty, so the object is not empty.

Thanks!

1

There are 1 answers

0
Николай Пузырь On BEST ANSWER

I don't know if it is possible using DTO. For that purpose I use Pipes. Like this:

Injectable()
export class ValidatePayloadExistsPipe implements PipeTransform {
  transform(payload: any): any {
    if (!Object.keys(payload).length) {
      throw new BadRequestException('Payload should not be empty');
    }

    return payload;
  }
}