【问题标题】:Joi requiring fields when it shoudnt beJoi 在不应该的时候需要字段
【发布时间】:2022-06-16 14:54:25
【问题描述】:

所以我使用@hapi/joi 17.1.1 进行了一些帖子验证,其中我有两个字段:文本字段和图片。我不要求任何字段,但它仍然说需要图片。

帖子验证

module.exports.postsValidation = (data) => {
  const schema = Joi.object({
    textfield: Joi.string().max(280),
    picture: Joi.string(),
  });

  return schema.validate(data);
};

posts.js(我使用验证)

router.post("/create", authenticateToken, async (req, res) => {
  try {
    if ((req.body.textfield == "") & (req.body.picture == "")) {
      return res.status(400).json("Fill one of the fields");
    }

    const { error } = postsValidation(req.body);
    if (error) return res.status(400).json(error.details[0].message);

    // Getting info for new post
    const newPost = new Post({
      textfield: req.body.textfield,
      picture: req.body.picture,
      ownerId: req.user._id,
    });

    // Saving new post
    await newPost.save();

    res.json(newPost);
  } catch (error) {
    res.sendStatus(500);
  }
});

谁能告诉我这是怎么回事?

【问题讨论】:

  • 错误到底是什么意思?

标签: javascript express validation joi


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
相关资源
最近更新 更多