【问题标题】:Joi validation : minimum length function is not workingJoi 验证:最小长度功能不起作用
【发布时间】:2019-03-05 14:08:54
【问题描述】:
const Joi = require('joi');
app.post('/api/courses', (req, res) => {
  const schema = {
    name: Joi.string().min(3).required()
  };
  const result = Joi.validate(req.body, schema);
  if (result.error) {
    res.status(400).send(result.error.details[0].message); 
    return;
  }
  const course = {
    id: courses.length + 1,
    name: req.body.name
  };
  courses.push(course);
  res.send(course);
});

当我在邮递员中发布一个空白对象时,需要 400 给出“名称”,但如果我发布“名称”:“1”,那么输出再次相同,而不是最小长度应该是 3 个字符。

【问题讨论】:

标签: node.js postman joi


【解决方案1】:

我无法复制该问题。如果您提供更多详细信息和失败示例,我们可能会提供帮助。

Joi.string().min(3).required().validate('a'); // ValidationError: "value" length must be at least 3 characters long

const objSchema = {name: Joi.string().min(3).required()};

Joi.validate({}, objSchema); // ValidationError: child "name" fails because ["name" is required]
Joi.validate({name: 'a'}, objSchema); // ValidationError: child "name" fails because ["name" length must be at least 3 characters long]

Joi.version; // '14.3.1'

【讨论】:

  • 对于上述场景,我发布了一个请求,其正文包含"name":"C",但没有发生任何应该引发错误的地方。
【解决方案2】:

检查您的模型并确保类型为字符串,如下所示:type: String。 这应该可以解决问题。 Joi 的 min() 函数似乎只对字符串进行操作。

【讨论】:

    猜你喜欢
    • 2017-11-18
    • 2016-12-17
    • 2020-12-11
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多