使用 joi 验证节点中的发布数据

Validate posted data in node with joi

所以我正在尝试验证我的 post 请求中的数据。 为此,我想使用 joi,但似乎我在某处遗漏了一些东西。
这是我的 post 请求:

app.post('/new-comp', async (req: any, res: any) => {
  const validation = schemaComp.validate(req.body)
  // need to declare an if/else statement to manage the error
  // for now, console.logs the info that data is not valid
  const data = await new CompetitionModel(req.body)
  console.log(validation)
  res.json(data)
})

正如我在评论中所说,我需要做一些 if/else 语句来管理验证(因为它似乎验证了数据,但不会停止 posting)

但是,我不确定该怎么做,我尝试过的所有方法都导致我出错。
我是这方面的初学者,如有任何建议,我们将不胜感激。
另外请在下面找到我的joi文件

export const Joi = require('joi')

export const schemaComp = Joi.object().keys({
  event_id: Joi.string().required(),
  compName: Joi.string().required(),
  place: Joi.string().required(),
  time: Joi.string().required(),
  subscriptions: [
    {
      id: Joi.string().required(),
      event_id: Joi.string().required(),
      name: Joi.string().required(),
      surname: Joi.string().required(),
    },
  ],
  date: Joi.date().required(),
  cost: {
    currency: Joi.string().required(),
    amount: Joi.number().required(),
  },
})

谢谢,

像这样验证,{ abortEarly: false } 抛出所有验证的错误

const { error } = schemaComp.validate(inputObj, { abortEarly: false });
  if (error) {
    // handle your errors here
  }