nodejs class-validator validating array of objects

ksdjlflksdflskdjf picture ksdjlflksdflskdjf · Mar 13, 2018 · Viewed 8.4k times · Source

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

Answer

NoNameProvided picture NoNameProvided · Mar 17, 2018

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.