Class-validator: feat: support multi-dimensional arrays

Created on 1 Mar 2020  路  3Comments  路  Source: typestack/class-validator

Hello, I am trying to validate the arrays in arrays but I could not find a correct method.

The structure looks like this:

class MyInnerDto {
 @IsString()
  name: string;
}

class TestDto {
@IsArray({ each: true })
 myArray:MyInnerDto[][];
}
feature

Most helpful comment

Maybe we should add an option maxDepth for this?

All 3 comments

Hello,

I've the same kind of issue with Map and Array values.
The test case below show validation error on nestedMap but not on nestedWithArray.
Is there another tips to validate this kind of structure ? or it's a bug ?

With class-validator": "0.11.0"

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

describe('NestedValidation', () => {
  class NestedClass {
    @IsString()
    name: string;

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

  class MasterClass {
    @ValidateNested({ each: true })
    nestedMap: Map<string, NestedClass>;

    @ValidateNested({ each: true })
    nestedWithArray: Map<string, NestedClass[]>;

    constructor(
      nestedMap: Map<string, NestedClass>,
      nestedWithArray: Map<string, NestedClass[]>,
    ) {
      this.nestedMap = nestedMap;
      this.nestedWithArray = nestedWithArray;
    }
  }

  describe('validation', () => {
    let validator: Validator;

    beforeAll(() => {
      validator = new Validator();
    });

    it('should validate nested object array', async () => {
      const nestedMap = new Map<string, NestedClass>();
      nestedMap.set('test', new NestedClass(42));
      const nestedMapWithArray = new Map<string, NestedClass[]>();
      nestedMapWithArray.set('test', [new NestedClass(42)]);
      const masterClass = new MasterClass(nestedMap, nestedMapWithArray);

      const errors = await validator.validate(masterClass);

      function expectNestedError(property: string) {
        const nestedError = errors.find(error => error.property === property);
        expect(nestedError).toBeDefined();
        expect(nestedError).toMatchObject({ property, target: masterClass, });
      }
      expectNestedError('nestedMap');
      expectNestedError('nestedWithArray');
    });
  });
});

Thanks

https://github.com/typestack/class-validator/pull/539 fixed multi-dimensional arrays for @ValidatedNested. But we should also support multi-dimensional arrays for cases like:

@IsNumber({}, {
    each: true
})
tags: number[][];

Note: I see one edge case here. What if I want to validate only first, second, third, ..., ... level of multi-dimensional array? E.g.:

@IsArray({}, {
    each: true
})
@IsNumber({ each: true })
tags: number[][][][][];

Maybe we should add an option maxDepth for this?

Was this page helpful?
0 / 5 - 0 ratings