1

I am trying to validate if an object passed is of a certain type.

Country object

class Country {
 code : string;
 name: string;
}

Validation code

  @IsNotEmpty()
  @IsNotEmptyObject()
  @IsObject()
  @ValidateNested()
  @Type(() => Country)
  country: Country;

@Type is imported from class-transformer

This is the answer which is found in many of the questions on stack overflow. eg : Class-validator - validate array of objects . It does not work for me. This is for a single object and not an array of objects.

Muljayan
  • 3,588
  • 10
  • 30
  • 54

1 Answers1

3

Try this:

Add the following to your controller: Ensure to have whitelist: true set to true. (This will strip down everything which is not in Country Schema definition)

@Post()
createExample(@Body(new ValidationPipe({ whitelist: true })) body: ExampleDto) {
   ...
}

Add your DTO like this:

class Country {
   @IsString()
   code : string;

   @IsString() // To make a field optional you can add @IsOptional
   name: string;
}

export class ExampleDto {

   // You do not require IsNotEmpty or because with IsString in Country you force it to be required.
   @ValidateNested()
   @Type(() => Country)
   country: Country;
}
Lars Flieger
  • 2,421
  • 1
  • 12
  • 34