Reputation: 5569
I am trying to enforce a validation on each item of an array.
As per my understanding (please correct me if I am wrong), class-validator does not support direct validation of arrays. It requires us to create a wrapper class.
So, the following are the classes:
export class SequenceQuery {
@MinLength(10, {
message: 'collection name is too short',
})
collection: string;
identifier: string;
count: number;
}
export class SequenceQueries{
@ValidateNested({ each: true })
queries:SequenceQuery[];
}
And the following is my controller:
@Get("getSequence")
async getSequence(@Body() query:SequenceQueries) {
return await this.sequenceService.getNextSequenceNew(query)
}
The following is the JSON that I am passing to the controller:
{"queries": [
{
"collection": "A",
"identifier": "abc",
"count": 1
},
{
"collection": "B",
"identifier": "mno",
"count": 5
},
{
"collection": "C",
"identifier": "xyz",
"count": 25
}
]}
But it doesn't seem to be working. It's not throwing any validation messages.
Upvotes: 3
Views: 11954
Reputation: 357
There is my complete solution/implementation in Nestjs
export class WebhookDto {
@IsString()
@IsEnum(WebHookType)
type: string;
@IsString()
@IsUrl()
url: string;
@IsBoolean()
active: boolean;
}
export class WebhookDtoArray {
@IsArray()
@ValidateNested({ each: true })
@Type(() => WebhookDto)
webhooks: WebhookDto[];
}
@MessagePattern('set_webhooks')
async setWebhooks(
@Payload('body') webhookDtoArray: WebhookDtoArray,
@Payload() data,
): Promise<Store> {
return this.storeManagementService.setWebhooks(
data.userPayload.id,
webhookDtoArray,
);
}
{
"webhooks": [{
"type": "InvoiceCreated",
"url": "https://test.free.beeceptor.com",
"active": true
},
{
"type": "InvoiceSettled",
"url": "https://test.free.beeceptor.com",
"active": true
},
{
"type": "InvoiceExpired",
"url": "https://test.free.beeceptor.com",
"active": true
}
]
}
Upvotes: 1
Reputation: 3007
class-validator does support array validation you have just to add what you already did in @ValidateNested({ each: true }), you have only to add each to the collection element:
export class SequenceQuery {
@MinLength(10, {
each: true,
message: 'collection name is too short',
})
collection: string;
identifier: string;
count: number;
}
source : Validation Array
Upvotes: 0
Reputation: 5569
I got the solution to the problem.
I was supposed to change my wrapper class to :
export class SequenceQueries{
@ValidateNested({ each: true })
@Type(() => SequenceQuery) // added @Type
queries:SequenceQuery[];
}
But I will leave the question open, just in case someone has an alternate solution as in not having to make a wrapper class.
Upvotes: 4