2个字段的自定义快速验证器

Custom express Validator for 2 fields

我有 2 个自定义验证器用于 2 个字段,emailphone

check('phone')
      .not()
      .isEmpty()
      .withMessage('Phone shouldnt be empty')
      .custom(async phone => {
        const phonechk = await User.findOne({ phone: phone });
        if (phonechk !== null) {
          return Promise.reject();
        }
      }).withMessage('Phone is already in use.')

以上 check 不会抛出任何错误,但这个 :

  check('email')
    .not()
    .isEmpty()
    .withMessage('Email shouldnt be empty')
    .isEmail()
    .withMessage('Email Should be Valid')
    .custom(async email => {
      const emailCheck = await User.findOne({ email: email });
      if (emailCheck !== null) {
        return Promise.reject();
      }
    }).withMessage('Email is already in use.'),

在浏览器上引发错误。

我在邮递员中测试 API 时注意到的事情 phone 验证抛出两个错误。

我就是这样处理我的 api 函数中的错误的:

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const arEr = errors.array();
    const newErrors = arEr.map(err => {
      return {
        field: {
          name: err.param,
          error: err.msg
        }
      }
    })
    res.status(401).json({
      message: 'Validation Error',
      errors: newErrors
    })
  }

来自浏览器的结果:

邮递员的结果:

两者都是相同的输入^

我正在使用 nuxt 和 express。

我使用自定义验证有什么问题吗?

事实证明问题不是来自 express-validator,因为我正在为 phone 个数字使用 vue-tel-iput 组件。该组件使用空格格式化 phone 数字,因此它以错误的形式提交了 phone。我使用 .replace(/\s+/g, "") 修剪了空格并且验证工作正常