class-validator validate request body as array
Asked Answered
J

0

0

Request Body:

[
 {
  fname: "fname",
  lname: "lname",
 },
 {
  fname: "fname1",
  lname: "lname1",
  grades: {
    quiz1: 75,
    quiz3: 85,
 },
 ...
]

Model:

export default class Student {
  @IsDefined()
  @IsString()
  fname!: string;

  @IsDefined()
  @IsString()
  lname!: string;

  @IsObject()
  @ValidateNested()
  @Type(() => Grades)
  grades!: Grades;
}
const body = plainToInstance(Student, req.body);

const valid = await validate(body, { skipMissingProperties: true }).then((errors) => {
  return errors.length > 0 ? errors.toString() : null;
});

The value of valid is always null. It doesn't seem like it is called.

Edit 1:

Another option i tried that did not work: as per: https://github.com/typestack/class-validator/issues/176#issuecomment-373933810

  • Creating a WrapperClass
export class WrapperClass {
  @IsDefined()
  @IsNotEmpty()
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => Student)
  records: Student[];

  constructor(records: Student[]) {
    this.records = records;
  }
}

and then

const payload = new WrapperClass(req.body);
const valid = await validate(payload, { skipMissingProperties: true }).then((errors) => {
    return errors.length > 0 ? errors.toString() : null;
});

console.log(valid); // always null
Jay answered 8/9, 2022 at 19:41 Comment(2)
You need to remove the .then part after await validate(payload, { skipMissingProperties: true }).Kulturkampf
That doesn't work, it jsut ends up being an empty array. Still not picking up the errors.Jay

© 2022 - 2024 — McMap. All rights reserved.