Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda