Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading