Mon, 01/16/2023 - 10:20
Here is a quick snippet for validating an array of objects
import { Type } from 'class-transformer';
import {
ArrayMinSize,
IsArray,
IsObject, ValidateNested
} from 'class-validator';
class ListItem {
@IsString()
name: string;
}
class List {
@IsArray()
@IsObject({ each: true })
@ValidateNested({message: ' must be an object with a required property "name" (string)'})
@Type(() => ListItem)
items: ListItem[]
}
Validation Errors
So the caller gets the following errors
Invalid Item Type, Array
Payload has an item of type array, instead of object.
{
items: [
[]
]
}
Result
[
"each value in items must be an object"
]
Note: The IsObject
validator is triggering the error here.
Invalid Item Type, String
Payload has a item of type string, instead of object.
{
items: [
""
]
}
Result
[
"must be an object with a required property "name" (string"
]
Note: The ValidateNested
validator is triggering the error here.
Missing Item Property
Payload with one item without a name
{
items: [
{}
]
}
Result
[
"items.0.name must be a string",
"items.0.name should not be empty"
]
Authored by
Tags