0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.