简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM