Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 404
RofLox Avatar asked Nov 29 '25 16:11

RofLox


1 Answers

You should do it like this:

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

    @ValidateNested({each: true})
    @IsArray()
    @IsNotEmpty()
    @Type(()=>CreateFloorDTO)
    public floors?: CreateFloorDTO[];
}
like image 165
Baterka Avatar answered Dec 02 '25 07:12

Baterka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!