【发布时间】:2021-04-26 10:46:46
【问题描述】:
我正在使用express-validator 在 API 中验证我的请求正文。
我想验证一个请求字段 - dataPoints 它应该是一个对象数组。我想检查每个对象中是否有一个键 - dataType 并且它的值是数组的一部分 - ["selection", "number", "text", "date"]。这是我的代码
validateParameters: () => {
return [
body("name").exists().withMessage("The name is required!"),
body("description").exists().withMessage("The description is required"),
body("dataPoints").isArray().withMessage("Datapoints can not be empty and must be an array!"),
body("dataPoints").custom(async (value) => {
if (value !== undefined & value.length > 0) {
value.forEach(function (dataPoint) {
var options = ["selection", "number", "text", "date"];
let dataValue = dataPoint.dataType ? dataPoint.dataType : "";
console.log(dataValue)
if (options.indexOf(dataValue.toLowerCase()) !== -1) {
return Promise.reject();
}
})
.withMessage("Invalid data point");
}
}),
]
},
当我通过错误的dataType 运行而不是Invalid data point 时,我目前收到此错误
{
"status": "error",
"errors": [
{
"message": "Cannot read property 'withMessage' of undefined"
}
]
}
我该如何解决这个问题?
另外,我如何确保dataPoints数组在提交之前至少包含一个对象,因为目前可以提交一个空的,这是错误的!
【问题讨论】:
-
我正在寻找如何在单个函数中使用所有验证而不是使用 body('username').isEmail(), body('password').isLength({ min: 5 }) 等。谁能帮忙?
标签: node.js express express-validator