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
.then
part afterawait validate(payload, { skipMissingProperties: true })
. – Kulturkampf