3

I'm trying to validate an array of objects. I tried the method mentioned here and that works fine for most cases. But the issue I'm facing is that when the array contains another array, the validation does not throw an error. While sending an array with a string the error displayed is must be either object or array. So I suppose it accepts an array. How do I stop it from letting through an array of arrays? I need it to only accept objects.

valid

{
    "user" : [{ "name" : "kate"}, {"name":"mike"}]
}

should be invalid

{
    "user" : [[]]
}

My validation code

export class UserInfo {
  @ApiProperty({ required: true })
  @IsNotEmpty()
  @IsString()
  name: string;
}

export class User {
  @IsOptional()
  @IsArray()
  @ArrayMinSize(1)
  @ValidateNested()
  @Type(() => UserInfo)
  user: UserInfo;
}
8
  • I'm not sure if this is outdated but on GitHub they say "Currently we do not have support for multidimensional arrays." github.com/typestack/class-validator/issues/… Commented Aug 29, 2022 at 11:12
  • Hmm I don't think I'm looking for multidimensional array validation. Commented Aug 29, 2022 at 11:15
  • 1
    Ahhh I see... Can you share your validation code? Commented Aug 29, 2022 at 11:17
  • 1
    Thank you! I tried a few things and it's behaves the same like you say... This is a good question / issue Commented Aug 29, 2022 at 11:39
  • 1
    @LarsFlieger it looks like this was already logged there - github.com/typestack/class-validator/issues/1597 Commented Aug 30, 2022 at 7:58

1 Answer 1

0

I don't understand why they're not fixing it, spent a few hours to find the "right way" to do it, without success

but this is what's my solution for the same problem but in my context

import { IsEnum, IsString, ValidateNested } from 'class-validator';
import { Transform, Type } from 'class-transformer';
import { POSTGRESQL_DATA_TYPES_ENUM } from 'src/table/constants';

const isArrayWithNoNestedArrays = (fields) => {
  // early return if fields is not an array
  if (!Array.isArray(fields.value)) return null;

  return fields.value.map((field) => {
    // replace array with not valid value
    // in my case it's null here
    if (Array.isArray(field)) return null;
    return field;
  });
};

class Field {
  @IsString()
  name: string;
  @IsEnum(POSTGRESQL_DATA_TYPES_ENUM)
  type: POSTGRESQL_DATA_TYPES_ENUM;
}

export class CreateTableDto {
  @IsString()
  name: string;
  @ValidateNested({ each: true })
  @Type(() => Field)
  @Transform(isArrayWithNoNestedArrays)
  fields: Field[];
}
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.