MichalLytek / class-transformer-validator

A simple plugin for class-transformer and class-validator which combines them in a nice and programmer-friendly API.
MIT License
200 stars 19 forks source link

Cannot validate array elements #34

Closed albertodiazdorado closed 3 years ago

albertodiazdorado commented 3 years ago

I can validate nested objects, and I can make sure that certain property is an array. However, the validator does not care if the elements in the array are valid or not. What am I forgetting here?

export class Album {
  @IsString()
  @Expose()
  @IsDefined()
  name!: string;
}

export class Photo {
  @IsNumber()
  @Expose()
  @IsDefined()
  id!: number;

  @Expose()
  @IsDefined()
  @IsArray()
  @Type(() => Album)
  albums!: Album[];
}

const object = {
  name: "Juan Ramon Riquelme",
  albums: [{
    noName: "Felipe"
  }]
}

// This line succeeds, but it should fail!
transformAndValidate(Photo, object, {
    transformer: { excludeExtraneousValues: true },
    validator: { forbidUnknownValues: true }
  }).then(console.log).catch(console.error);

I have written a complete reproducer and pushed it here: https://gitlab.com/albertodiazdorado/class-transform-validator-issue To reproduce:

git clone https://gitlab.com/albertodiazdorado/class-transform-validator-issue.git
pushd class-transform-validator-issue
yarn install # or npm install
yarn start   # or npm start
MichalLytek commented 3 years ago

Search for class-validator solution like each: true or @ValidateNested

albertodiazdorado commented 3 years ago

@MichalLytek that was the solution, thank you very much!

I fixed the example by adding the decorators

@IsInstance(Album, {each: true})
@ValidateNested()

to the albums field. Works like a charm.

PS: And thank you very much for the quick answer!! :D