2

I have a array of objects that looks like this

[{
  name: 'some name'
  catId: 2,
}, {
  name: 'another name'
  catId: 3,
}]

How can I validate using class-validator so that the name field is required and minimum 2 chars long in each object?

Thanks

Striped
  • 2,544
  • 3
  • 25
  • 31
  • This was helpful for me https://stackoverflow.com/questions/58343262/class-validator-validate-array-of-objects – frederj Dec 21 '20 at 17:05
  • this too https://stackoverflow.com/questions/59838601/class-validator-doesnt-validate-arrays – frederj Sep 01 '21 at 14:50

1 Answers1

6

To validate an array of items, you need to use @ValidateNested({ each: true }).

A complete example:

import { validate, IsString, MinLength, ValidateNested } from 'class-validator';

class MySubClass {
  @IsString()
  @MinLength(2)
  public name: string;

  constructor(name: string ){
    this.name = name;
  }
}

class WrapperClass {
  @ValidateNested({ each: true })
  public list: MySubClass[];

  constructor(list: MySubClass[]) {
    this.list = list;
  }
}

const subClasses = Array(4)
    .fill(null)
    .map(x => new MySubClass('Test'))

subClasses[2].name = null;

const wrapperClass = new WrapperClass(subClasses);
const validationErrors = await validate(wrapperClass);

This will log a validation error for subClasses[2] as expected.

NoNameProvided
  • 8,608
  • 9
  • 40
  • 68