我使用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");
}
}),
]
},{
"status": "error",
"errors": [
{
"message": "Cannot read property 'withMessage' of undefined"
}
]
}我该如何解决这个问题?
另外,我如何确保dataPoints数组在提交前至少包含一个对象,因为目前可以提交一个空的对象,这是错误的!
发布于 2021-04-26 20:05:27
您应该在自定义验证器中使用抛出新的错误,而不是使用.withMessage方法。下面是一个示例:
body("properties")
.custom((value) => {
if (_.isArray(value)) {
if (value.length !== 0) {
for (var i = 0; i < value.length; i++) {
if (
/^[ \u0600-\u06FF A-Za-z ][ \u0600-\u06FF A-Za-z ]+$/.test(
value[i]
)
) {
if (i === value.length - 1) {
return true;
} else {
continue;
}
} else {
throw new Error("Invalid data point");
}
}
} else {
return true;
}
} else {
throw new Error("Invalid data point");
}
})
.optional(),如果你想通过你的验证器,你应该返回真正的
https://stackoverflow.com/questions/67265221
复制相似问题