RofLox
RofLox

Reputation: 87

Class-validator is ignoring nested objects

I am using NestJs framework for my project. In my controller I accept POST request and through ValidationPipe I transform body into my CreateHouseDTO. ValidationPipe is using whitelist and transform.

When I try api with JSON like this:

{
    "name": "Test",
    "floors": [
        {
            "name": "floor1",
            "rooms": [
                {
                    "name": "room1"
                },
                {
                    "name": "room2"
                }
            ]
        }
    ]
}

This is what my app logs (console.log output):

CreateHouseDTO{
    name:'Test',
    floors[ {} ]
}

It does even validate the nested objects when I make some mistakes in them. For example if I set name property in Floor object to Null or to some number without quotes.

Is it a bug or am I doing something wrong? Please help me.

My code:


//My DTOs
import {ValidateNested, IsString, IsArray} from "class-validator";
import {Body, Controller, Post} from "@nestjs/common";

export class CreateHouseDTO {
    @IsNotEmpty()
    @IsString()
    public name?: string;

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    public floors?: CreateFloorDTO[];
}

export class CreateFloorDTO {
    @IsString()
    @IsNotEmpty()
    public name?: string;

    @ValidateNested({each: true})
    @IsNotEmpty()
    @IsArray()
    public rooms?: CreateRoomDTO[];
}

export class CreateRoomDTO {
    @IsString()
    @IsNotEmpty()
    public name?: string;
}

//My Controller
@Controller("house")
export class HouseController {
    @Post()
    async create(
        @Body()
            body: CreateHouseDTO
    ) {
        console.log(body); //output I mentioned
        return body;
    }
}

Upvotes: 2

Views: 4807

Answers (1)

Baterka
Baterka

Reputation: 3724

You should do it like this:

export class CreateHouseDTO {
    @IsNotEmpty()
    @IsString()
    public name?: string;

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    @Type(()=>CreateFloorDTO)
    public floors?: CreateFloorDTO[];
}

Upvotes: 9

Related Questions