Home > Software engineering >  How to validate arrays/objects in express-validator using body(), checking only the specified fields
How to validate arrays/objects in express-validator using body(), checking only the specified fields

Time:04-05

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: [email protected],
    position: Actor,
    salary: low
    },
    
    {employeeNumber: 12344,
    firstName: Chris,
    lastName: Rock,
    trEmail: [email protected],
    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.

CodePudding user response:

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;
};
  • Related