Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

268
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda