Home > Software design >  How to validate array of literals using class-validator and class-transformer with plainToInstance o
How to validate array of literals using class-validator and class-transformer with plainToInstance o

Time:10-29

My validation is not kicking in when using plainToInstance to cast literals to classes. The transform seems to work as I have Array(3) [Foo, Foo, Foo] after plainToInstance() yet the validation shows no errors:

Codesandbox Demo

import { plainToInstance } from 'class-transformer';
import { IsEmail, validate } from 'class-validator';

class Foo {
  @IsEmail()
  email: string;
}

(async () => {
  const data: Foo[] = plainToInstance(Foo, [{ email: '' }, { email: '1@' }, { email: '[email protected]'}]);
  
  // no errors
  let errors = await validate(data); // no errors (errors = [])
  console.info(errors);

  // this errors
  const foo = new Foo();
  errors = await validate(foo); // errors (errors Array(1) [ValidationError])
  console.info(errors);
})();

What step am I missing?

CodePudding user response:

It seems like validate is not meant to handle arrays of classes. It shows no error because the array does not have any meta data associated with it which would trigger any validation.

What you probably want to do is to validate each object individually.

let errors = await Promise.all(data.map(d => validate(d)))
  • Related