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

422
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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;
};
about 4 years ago · Juan Pablo Isaza Denunciar
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