简体   繁体   中英

Is there's a way to validate unknown keys with JOI on nested payloads?

I have a middleware that validates a incoming request using Joi.

export default (schema: any) => async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validation = schema.validate(req, { abortEarly: false })

    if (validation.error) throw validation.error

    return next()
  } catch (error) {
    return res.status(400).json({ error: error.details })
  }
}

For testing, propouse, my schema is as follow

const schema = Joi.object({
  headers: Joi.object()
    .keys({
      page: Joi.string().required()
    })
    .unknown(true)
    .label('headers'),
  body: Joi.object({
    page: Joi.string().required()
  })
})

I'm testing this function with Postman. When I do not send the header it fails but show this following errors:

  • 'user-agent': 'PostmanRuntime/7.29.0'
  • accept: ' / ',
  • 'accept-encoding': 'gzip, deflate, br',
  • connection: 'keep-alive'

I want to be able to validate only the 'page' field on the schema, and ignore the anyn other field above.

Change your validation and add stripUnknown option to true:

const validation = schema.validate(req, { abortEarly: false, stripUnknown:true })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM