Node.js 快速验证器:我们如何验证对象密钥?
我在使用express validator验证带有两个键的对象时遇到了一个问题。我的方法如下Node.js 快速验证器:我们如何验证对象密钥?,node.js,express,joi,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.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(),
在请求正文中我将我的联系人发送为,
联系人:{“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`));
下面是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"}}'
此卷曲将返回:
{
"errors": [
{
"value": "1sdf23",
"msg": "Country code must be numeric.",
"param": "contact.code",
"location": "body"
}
]
}
您似乎没有将
参数
作为数字。请检查其类型并尝试将其转换为数字。错误消息告诉您,这两个值都是空的“值”:“”
,因此不是数值。您能否验证req.body
是否已定义?您是否设置了主体解析器
?@eol我已经实现了主体解析器,并且req.body也被定义为rest主体密钥正在正确验证。但我只有这把联系钥匙有问题。非常感谢@eol的详细解释。这对我很管用