node.js - Express-validator:我们如何验证对象键?

标签 node.js express joi express-validator

我在使用 express-validator 验证具有两个键的对象时遇到了问题。我的方法如下所示。

  check('contact.code')
    .trim()
    .isNumeric()
    .withMessage('Country code must be numeric.')
    .bail()
    .isLength({min: 1, max: 4})
    .withMessage('Invalid country code.')
    .bail(),
  check('contact.number')
    .trim()
    .isNumeric()
    .withMessage('Phone number must be numeric.')
    .bail()
    .isLength({max: 10, min: 10})
    .withMessage('Phone number must be 10 digits long.')
    .bail(),

req.body 中,我发送我的联系方式, 联系人:{"code": "91", "number":"9087654321"} 但我收到错误:

{
    "errors": [
        {
            "value": "",
            "msg": "Country code must be numeric.",
            "param": "contact.code",
            "location": "body"
        },
        {
            "value": "",
            "msg": "Phone number must be numeric.",
            "param": "contact.number",
            "location": "body"
        }
    ]
}

我已经用谷歌搜索过了,但没有成功。请帮我解决这个问题。 任何形式的帮助将不胜感激。

最佳答案

如下设置清理/验证检查中间件似乎工作正常:

const validationResult = require('express-validator').validationResult;
const check = require('express-validator').check;

const express = require('express');
const app = express();
app.use(express.json());

app.post('/test-validation',
  [
    check('contact.code')
      .trim()
      .isNumeric()
      .withMessage('Country code must be numeric.')
      .bail()
      .isLength({ min: 1, max: 4 })
      .withMessage('Invalid country code.')
      .bail(),
    check('contact.number')
      .trim()
      .isNumeric()
      .withMessage('Phone number must be numeric.')
      .bail()
      .isLength({ max: 10, min: 10 })
      .withMessage('Phone number must be 10 digits long.')
      .bail(),
  ], (req, res) => {
    const errors = validationResult(req).array();
    if (errors && errors.length) {
      console.log(errors);
      res.status(400).json({ errors });
    } else {
      res.status(201).end();
    }
  });

app.listen(3000, () => console.log(`Server running`));

Here's codesandbox 上的这段代码和示例 curl:

curl --location --request POST 'https://mwjbg.sse.codesandbox.io/test-validation' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Cookie: __cfduid=d7012caa5f36c195967d2fc26d3b7bd431595933685' \
--data-raw '{ "contact": {"code": "1sdf23", "number":"9087654321"}}'

这个 curl 将返回:

{
    "errors": [
        {
            "value": "1sdf23",
            "msg": "Country code must be numeric.",
            "param": "contact.code",
            "location": "body"
        }
    ]
}

关于node.js - Express-validator:我们如何验证对象键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63121567/

相关文章:

joi - 指定字段名称而不是 "value"

javascript - 为什么在 JavaScript 中数组的大小打印为零?

node.js - Jade 中的多个逻辑 OR 运算符

mysql - 哪些可能的原因会导致nodejs中的mysql队列达到限制问题

javascript/express.js 未在自定义验证回调函数中返回路由函数

javascript - 如何强制一个属性仅在另一个属性为真时出现?

html - 如何使用 EJS 模板有条件地显示 HTML?

javascript - 在 Python 中嵌入 Node.js

angularjs - Excel 下载在 MEAN stack 应用程序中不起作用

javascript - Joi 数组验证忽略所需的嵌套键