[英]Validate an array of object using express-validator
我正在使用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");
}
}),
]
},
當我運行的,而不是我目前得到這個錯誤Invalid data point
時,我傳遞一個錯誤dataType
{
"status": "error",
"errors": [
{
"message": "Cannot read property 'withMessage' of undefined"
}
]
}
我該如何解決?
另外,在提交之前,我如何確保dataPoints
數組至少包含一個對象,因為目前可以提交一個空對象,這是錯誤的!
使用我的github鏈接,你會得到完美的答案。 我已經為此使用 express-validator 在 nodejs 中創建了一個小項目
https://github.com/Sagar-Prajapati/ValidateRegistration/tree/master
您應該在自定義驗證器中使用throw new Error而不是 .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(),
如果你想通過你的驗證器,你應該返回 true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.