Search code examples
validationnestjsdtoclass-validator

Is it possible to validate top-level array by class-validator in NestJS?


So I have NestJS with global validation pipe: app.useGlobalPipes(new ValidationPipe())

Is it possible to validate TOP LEVEL ARRAY like?

[{
  "id":1,
  "name":"John"
}, {
  "id":2,
  "name":"Jane"
}]

I've read the docs, but they suggest only nested array validation, so payload needs to be like

{
  "users": [
    {
      "id": 1,
      "name": "John"
    },
    {
      "id": 2,
      "name": "Jane"
    }
  ]
}

But question is about validation top-level array, not nesting it into additional variable.

For now my best idea is extend ValidationPipe to translate payload from 1st example to payload in 2nd example. But I'm looking something like yup.array() which works fine at top level and wondering if class-validator missing top-level array validation, or if I'm missing something from docs.


Solution

  • As the docs mention there's the ParseArrayPipe which ends up running the ValidationPipe against an array of the provided DTO type. You must bind this pipe manually due to how Typescript handles the reflection of generics (which arrays are considered to be). This is why it's usually preferred to make the array a property of an object rather than a top-level value