如何使用 Joi 验证电子邮件

How to validate an email using Joi

我正在学习这个 Node.js 教程,但是 .validate 方法给了我一个错误
Link: https://www.youtube.com/watch?v=RLtyhwFtXQA
时间戳:2:07:40

代码:

app.post("/", (req, res) => {
  console.log(req.body);
  const schema = Joi.object().keys({
    email: Joi.string().trim().email().required(),
    pswd: Joi.string().min(5).max(10).required()
  });
  Joi.validate(req.body, schema, (err, result) => {
    if(err) console.log("Error" + err);
    else {
      console.log(result);
      res.send("Successfully Posted Data");
    }
  });
});

错误信息:TypeError: Joi.validate is not a function

该视频是 2 年前发布的,所以 Joi 可能更改了函数,因为 VS Code 也没有将 .validate 显示为 Joi 的函数。

不确定您使用的 Joi 版本,但最新的 Joi 通过模式而不是 Joi 进行验证,例如:

schema.validate(req.body);

我相信你想要这样的东西 并假设 req.body 中有 emailpswd

如果你想更深入地了解,你可以阅读文档https://joi.dev/api/

const { value, error } = schema.validate(req.body);
if(error) console.log("Error" , error);
else {
      console.log(value);
      res.send("Successfully Posted Data");
}