node.js - 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中,我将我的联系人发送为,
contact: {"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"
}
]
}
我已经用谷歌搜索了它,但没有得到任何成功。请帮我解决这个问题。任何形式的帮助将不胜感激。
解决方案
如下设置 sanitazion/validationcheck
中间件似乎工作正常:
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`));
这是codeandbox上的这段代码和一个示例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"
}
]
}
推荐阅读
- c# - Xamarin 表单中的 ObservableCollection 问题
- javascript - 从类的方法返回查询结果
- python - pip安装报错:包目录不存在
- arrays - 关于二维字符数组,哪个答案是正确的
- javascript - 如何在使用 FETCH 和 Vanilla Javascript 时解决 CORS(Access-Control-Allow-Origin)和 CORB 问题
- flutter - Flutter - 未处理的异常:类型'String'不是'index'类型'int'的子类型
- python - 使用一组方法和属性扩展独立类(包装器)
- c# - Xamarin Forms 将图像作为 POST 上传到网页
- android - 自动授予 Uri 权限
- python - Excel 编码影响 pandas 过滤