Joi 错误:ValidationError:“值”必须是对象类型

问题描述

我想知道为什么 JOI 会同时返回错误和值:

implementation 'org.springframework.boot:spring-boot-starter-validation'
app.post("/api/courses",(req,res) => {
  const { error,value } = validateStuff(req.body.name);
  console.log(`error: ${error}
  value: ${value}`);

validateStuff = (course) => {
  const schema = Joi.object({
    name: Joi.string().min(3).required(),});
  return schema.validate(course);
};

输出

错误:验证错误:“值”必须是对象类型

值:al(我的帖子输入)

解决方法

如果不想出错,则需要将 req.body 传递给 validateStuff。

您的代码立即传递来自 name 属性的字符串

或者您可以将您的 Joi 架构更改为 const Joi.string().min(3).required()

您的问题表明您想知道为什么 schema.validate 会同时返回错误和值。

当像 const { error,value} = schema.validate() 那样解构时,您可以执行以下操作,因为您可能在运行时出现错误或没有错误。

if (error) {
  // handle error
  // passed value might be needed
} else {
  // validation successful
}