【问题标题】:difference between {key:""} and {key:" "}, json file?{key:""} 和 {key:""} 的区别,json 文件?
【发布时间】:2019-09-19 03:18:57
【问题描述】:

我正在尝试在我的 express 路由器上实现验证,问题是当我通过 {title:""} 时,express-validator 没有抛出错误,但是当我通过 {title:""} 时它可以工作。

exports.postValidatorCheck = [
  check("title", "The title must not we empty").isEmpty(),
  check("title", "The Length of the Title should be in greater then 10").isLength({
    min: 10,
    max: 1500
  }),
  function(req, res, next) {
    let errors = validationResult(req);
    console.log(errors);
    if (!errors.isEmpty()) {
      const firstError = errors.errors.map(err => err.msg)[0];
      return res.status(400).json({ error: firstError });
    }
    next();
  }
];

jSON 文件:

{
"title":"",
"body":"This is a new Post"
} 

没有错误

JSON 文件

{
"title":" ",
"body":"This is new post"
}

如预期的错误。

【问题讨论】:

    标签: javascript json express middleware express-validator


    【解决方案1】:

    验证应该使用否定:

    check("title", "The title must not we empty").not().isEmpty()
    

    这将确保title 不为空,我认为这是您的意图。

    【讨论】:

      【解决方案2】:

      首先,"" 是一个空字符串。 " " 不是;它包含一个空格字符。如果您想将任何空格算为空,则应使用regex solution

      至于您的实际问题,当您应该测试 not().isEmpty() 时,您正在测试 isEmpty()

      【讨论】:

      • 所以,当我通过 {title:""} express-validator 应该抛出一个错误,但它没有,它验证标题并继续前进。
      猜你喜欢
      • 2011-04-20
      • 2015-10-12
      • 2020-11-21
      • 2013-12-02
      • 2019-02-13
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多