middleware icon indicating copy to clipboard operation
middleware copied to clipboard

validating all parts of the request

Open ryanleecode opened this issue 1 year ago • 1 comments

zod validation is sequential right now. Meaning if the headers are invalid it will fail-first and not return any information about other parts of the request that might be invalid. Also the zod error has no context about the origin. you cant tell if its from header, query, body, etc by default.

ryanleecode avatar Mar 24 '24 06:03 ryanleecode

Hi @ryanleecode

zod validation is sequential right now.

Hono's Validator validates the specified content, param, header, query, etc. By sequential, do you mean when use multiple validators?

In that case, how about using a custom Hook?

app.get(
  '/posts/:id',
  zValidator(
    'param',
    z.object({
      id: z.coerce.number()
    }),
    (result, c) => {
      if (!result.success) {
        return c.json(
          {
            'error in': 'param'
          },
          400
        )
      }
    }
  ),
  zValidator(
    'query',
    z.object({
      page: z.coerce.number()
    }),
    (result, c) => {
      if (!result.success) {
        return c.json(
          {
            'error in': 'query'
          },
          400
        )
      }
    }
  ),
  (c) => {
    const { page } = c.req.valid('query')
    // ...
    return c.json({
    })
  }
)

yusukebe avatar Mar 28 '24 13:03 yusukebe