Skip to content

fix: ValidateNested always fails with optional/nullable values even when IsOptional({each:true}) is set #2587

Open
@Woodz

Description

@Woodz

Description

Minimal code-snippet showcasing the problem

class Bar {
  @IsAlphanumeric()
  baz: string;
}

class Foo {
  @IsOptional({ each: true })
  @ValidateNested({ each: true })
  bars: Map<string, Bar | null> | null;

  @IsOptional({ each: true })
  @ValidateNested({ each: true })
  abc: (Bar | null)[];
}

const foo = new Foo();
const bar1 = new Bar();
bar1.baz = "Hello";
const bar2 = new Bar();
bar2.baz = "World";
foo.bars = new Map([
  ["a", bar1],
  ["b", bar2],
  ["c", null],
]);
foo.abc = [bar1, bar2, null];

(async function () {
  console.dir(JSON.stringify(foo));
  const validationErrors = await validate(foo);
  console.dir(JSON.stringify(validationErrors));
})();

https://codesandbox.io/p/sandbox/class-validator-forked-kfxxkq?file=%2Fsrc%2Findex.ts%3A38%2C46

Expected behavior

Since we have @IsOptional({ each: true }), I expect these fields to not have any validation errors when containing nulls

Actual behavior

Returns validation errors:

  1. each value in nested property bars must be either object or array
  2. each value in nested property abc must be either object or array

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