最小函数的 Joi 验证问题

Joi validation issue with min function

我在使用 Joi 的 express.js 中使用了以下代码,并希望验证名称长度必须至少为 3 并且不能为空,但最小值不起作用,因此需要您的帮助。

const Joi = require('@hapi/joi');
const express = require('express');

const app = express();

app.use(express.json());

//Define static array
const courses = [
  {id: 1, name:'course 1'},
  {id: 2, name:'course 2'},
  {id: 3, name:'course 3'},
];

app.get('/api/courses', (req, resp) => {
   resp.send(courses);
});

app.post('/api/courses', (req, resp) => {
   const schema = Joi.object({
     name: Joi.string()
           .max(3).required
           .messages({
               'string.max': 'Name should be max 3 characters..',
               'any.required': 'Name must not be empty...',
     }),
   }); 

   const { error } = schema.validate(req.body);

   if(error) {
     resp.status(400).json( {error: error.details[0].message});
     return;
   }
   const course = {
     id: courses.length + 1,
     name: req.body.name
   };

   courses.push(course);
   resp.send(course);
});

在您的问题中您说 "name length must be minimum 3",但在您的架构中应用了最大规则。

还有你忘记在required后面加括号了

您需要具有“最小、空和必需规则”的此架构。

  const schema = Joi.object({
    name: Joi.string()
      .min(3)
      .empty()
      .required()
      .messages({
        "string.min": `Name should be min {#limit} characters..`,
        "string.empty": "Name cannot be an empty field",
        "any.required": "Name is required"
      })
  });

案例 1: 没有名称字段

要求:

{

}

响应:

{
    "error": "Name is required"
}

案例 2:名称为空

要求:

{
  "name": ""
}

响应:

{
    "error": "Name cannot be an empty field"
}

案例3: 名字是2个字符

要求:

{
  "name": "AB"
}

响应:

{
    "error": "Name should be min 3 characters.."
}

还要确保您发送请求 body,原始 JSON 像这样:

还要确保您拥有此 Content-Type header 且值为 application/json