I am trying to check if the products sent from the client is an array and not empty using a custom validator in express-validator.
However when I send the correct json, I still get an error which looks like this:
error returned from API:
{
"error": [
{
"value": [
{
"productId": "548fefewrTNH563",
"quantity": 3
},
{
"productId": "548fefewrT4354563",
"quantity": 2
}
],
"msg": "Invalid value",
"param": "products",
"location": "body"
}
]
}
The json sent in POST request
{
"userId" : "61923f2df64756f1df629a7c",
"products" : [
{
"productId" : "548fefewrTNH563",
"quantity" : 3
},
{
"productId" : "548fefewrT4354563",
"quantity" : 2
}
],
"amount" : "2",
"address" : "dfjkdj3djfnjj4jndfn"
}
Code on the validator file:
const {check , validationResult} = require('express-validator');
exports.validateCreateOrder = [
check("userId", "UserId is missing").not().isEmpty(),
check("products").custom(products=>{
if(!Array.isArray(products))throw new Error('Products need to be an array')
if (products.length == 0 ) throw new Error ('Product array cant be empty')
}),
check("amount", "Amount is missing").not().isEmpty(),
check("address", "Address is missing").not().isEmpty(),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty())
return res.status(400).json({ error: errors.array() });
next();
},
]