【问题标题】:No errors with express-validator isEmptyexpress-validator isEmpty 没有错误
【发布时间】:2020-06-15 02:47:11
【问题描述】:

我在 expressjs 应用程序中使用 express-validator 5.2.0。我在表单数据上实现了验证。但它不会捕获错误并给出空的错误对象。当验证运行时,它在我提交空表单时显示“无错误”。它应该遵循错误路径并且应该显示错误。

var express = require('express');
var router = express.Router();
const { check, validationResult } = require('express-validator/check');

router.post('/register', [
  check('firstName', 'First Name is required').isEmpty(),
  check('lastName', 'Last Name is required').isEmpty(),
  check('username', 'User Name is required').isEmpty(),
  check('password', 'Password is required').isEmpty()
], (req, res, next)=>{
  let errors = validationResult(req);
  if (!errors.isEmpty()) {
    console.log(errors.mapped());
    console.log("errors")
    return res.render('auth/register', { errors: errors.mapped() })
  }else{
    console.log('no errors')
    return res.render('auth/login');
  }

【问题讨论】:

    标签: express express-validator


    【解决方案1】:

    check('firstName', 'First Name is required').isEmpty() 强制 firstName 为空。
    您需要将最后一部分更改为 .not().isEmpty(),以便反转 isEmpty 验证器。

    您可能也感兴趣:https://github.com/express-validator/express-validator/issues/476

    【讨论】:

    • 如果我像这样链接: .not().isEmpty().isAlphanumeric() ...它会恢复链的 isAlphanumeric() 部分...还是只到达下一个实例链条?
    【解决方案2】:

    在您的 sn-p 中,您没有添加验证器来检查值是否不为空。 你可以这样做:

    check('firstName', 'First Name is required').notEmpty()
    

    .notEmpty() 添加一个验证器来检查一个值是否不为空;即长度为 1 或更大的字符串。

    https://express-validator.github.io/docs/validation-chain-api.html#notempty

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 2019-11-06
      • 2022-08-05
      • 1970-01-01
      • 2020-01-23
      • 2020-09-07
      相关资源
      最近更新 更多