class-validator with nestjs prevent creating missing fields with undefined when used with @IsOptional() decorator

70 Views Asked by At

I have a DTO that looks like this:

export class UpdateXXXDto {
  @IsString()
  @IsNotEmpty()
  field1: string;

  @IsOptional()
  @IsString()
  field2: string;

  @IsOptional()
  @IsString()
  field3: string;
}

As defined with an update request i am able to send a payload with only field1 as it is required, but for field2 and field3 i don't have to send them with the payload. The problem i encountered is that when i send a payload with { "field1": "exp" } i got a valid object but with { "field1": "exp", "field2": undefined, "field3": undefined }. I don't want that class-validator adds those optional fields at all ?

The documentation doesn't show any API to handle this case if i didn't miss anything! So i am asking the question to make sure if this is already possible ?

1

There are 1 best solutions below

0
Walkance On BEST ANSWER

I struggled with the same issue and finally found the solution. You need to ensure that ValidationPipe option transformOptions.exposeUnsetFields is set to true in combination with transform: false.

 /** app is nest application object */
 app.useGlobalPipes(
    new ValidationPipe({
      transform: false,
      transformOptions: {
        exposeUnsetFields: false
      }
    })
 );

I did not found in the nestjs docs, but options defined within transformOptions are directly passed in the plainToClass function of the class-transform package.

From the related docs:

When set to true, fields with undefined as value will be included in class to plain transformation. Otherwise those fields will be omitted from the result.

DEFAULT: true