Skip to content

fix: @ValidateNested does not work recursively #2677

Description

@jangxx

Description

When using @ValidateNested() on a class that's nested more than one level, the validation passes class instances with missing properties.

Minimal code-snippet showcasing the problem

import { IsString, ValidateNested, validateOrReject } from "class-validator";
import { plainToInstance, Type } from "class-transformer";
import "reflect-metadata";

class Level3 {
	@IsString()
	aString: string;
}

class Level2 {
	@Type(() => Level3)
	@ValidateNested()
	level3: Level3;
}

class Level1 {
	@Type(() => Level2)
	@ValidateNested()
	level2: Level2;
}

const instance = plainToInstance(Level1, { level2: {} });

validateOrReject(instance);

console.log(instance);

Expected behavior

This snippet should throw an error, since {} clearly isn't a valid Level2 class.

Actual behavior

The validation passes and the output reads Level1 { level2: Level2 {} }. Adding @IsDefined() to the level3 property in the Level2 class makes the validator throw an error as expected. Similarly, adding another property with a decorator like @IsString() someString: string will also correctly fail the validation, because the key is missing. But for some reason, the level3 property with only the @ValidateNested() decorator is ignored and validation passes.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs triageIssues which needs to be reproduced to be verified report.type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions