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

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.