Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

263
Views
Unexpected error returned from express-validator while using custom validator

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();
},

]

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!