NestJS validate POST body when it's other than object type

1.1k views Asked by At

I need to validate a list of emails (array of strings) that are passed via POST. Using something like validation pipes and class-validator would be awesome (however in the official docs I only found examples of objects validation through DTOs and validation of primitive types but for GET requests).

Here is how my method looks like in the controller:

@Post()
async submit(@Body() emails: string[]) {
}
1

There are 1 answers

0
Jay McDoniel On

If it's just being passed directly like that, then there's not much you can do besides implement a custom pipe. If you are able to change the payload structure I would suggest it to something like

export class PostDTO {
  @IsEmail({ each: true })
  emails: string[]
}

And use

@Post()
async submit(@Body() { emails }: PostDTO) {}

so that Nest's ValidationPipe can read the metadata of the post.