1

I want to validate a list of nested Object @ the request:

export class Room {
  @ApiProperty()
  @IsNotEmpty()
  @IsString()
  name: string;

  @ApiProperty({ type: [RoomMate] })
  @IsNotEmpty()
  @IsArray()
  @ValidateNested({ each: true })
  roomMates: RoomMate[];
}

The documation linked at nest.js (https://github.com/typestack/class-validator#validating-arrays) only talks about nested Objects, but not about a List of nested objects

If I execute the code above it says:

{
  "statusCode": 400,
  "message": [
    "0.an unknown value was passed to the validate function"
  ],
  "error": "Bad Request"
}

If I delete "@ValidateNested({ each: true })" it won't be validated (you could pass eg Cats & Dogs instead of RoomMates)

Any idea?

1 Answer 1

2

For @ValidateNested, I've found you need to specify an @Type as well:

  @ApiProperty({ type: [RoomMate] })
  @IsNotEmpty()
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => RoomMate)
  roomMates: RoomMate[];

The class-validator README examples assume you're working with classes, and there's a section on validating plain objects. This example in the class-transformer README shows using @Type() to specify the type of a nested object.

Also, makes sure RoomMate is a class and not just a TypeScript interface.

See this issue on class-validator for some more information.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you VEEEERRRY much .... yes now it works. There are totaly 3 modules which contains a decorator "Type" I've choosen this: import { Type } from 'class-transformer'; ... and now it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.