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

654
Visualizações
How to validate arrays/objects in express-validator using body(), checking only the specified fields?

I have my field names in an array like these:

const baseFields = [
'employeeNumber',
'firstName',
'lastName',
'trEmail',
'position'
];

Those are the input fields I only have to care about being validated.

In the request body, I receive an array of objects. Example:

   {employeeNumber: 12343,
    firstName: Will,
    lastName: Smith,
    trEmail: smith@will.com,
    position: Actor,
    salary: low
    },
    
    {employeeNumber: 12344,
    firstName: Chris,
    lastName: Rock,
    trEmail: rock@chris.com,
    position: stuntman,
    salary: ''
    }

I want to validate this array with only the concern fields in the baseFields array.

This is my current validator code. I've found out that I can use wildcards in order to validate arrays.

const existsOptions = {
    checkNull: true,
    checkFalsy: true
};

const postRequiredFields = () => {

    const validators = [];

    const validator = body('*.*')
    .exists(existsOptions)
    .bail()
    .isString();
    validators.push(validator);
    
    return validators;
};

Using this const validator = body('*.*') will check all of the fields in the array of objects in the body. Since I can get this message:

{ value: '',
  msg: 'Invalid value',
  param: '[1].salary',
  location: 'body' }

You see, salary field is being checked. It returned invalid value because the second index in the array has the salary set to '' or empty. But again, the salary field is not one of the fields that I need to validate.

So I tried something like this body('baseFields*.*') to check the whole array of objects but only the concern fields but it won't work. I couldn't find the right wildcard pattern for my scenario online. The documentation also says very little.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

to check an object in an array, use: *.key

and then you can just loop your keys and add them dynamically:

const postRequiredFields = () => {

    const validators = [];

    baseFields.map((key) => {
        const validator = body(`*.${key}`)
            .exists(existsOptions)
            .bail()
            .isString();
        validators.push(validator);
    });

    return validators;
};
over 4 years ago · Santiago Trujillo Relatório
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