Search code examples
node.jsexpressexpress-validator

Using chain validation to check existence of optional fields with Express Validator


I am trying to check for the existence of an optional field in an API request, and if that field exists, perform a nested validation to check if two other fields (one or the other, or implicitly both) exist inside of it. I am using Express Validator to try and accomplish this task.

// Sample request body
{
  <...>
  thresholds: {
    min: 3,
    max: 5
  }
}

// (Attempted) validation chain
check('thresholds').optional()
      .custom( innerBody => {
          console.log('THRESHOLDS', innerBody);
          oneOf([
              check('innerBody.min').optional(),
              check('innerBody.max').optional()
          ]);
      })

The above snippet is part of a larger validation chain I'm validating the full request body on. I also tried removing the innerBody. string from the inner checks but still no luck. I am console.loging the threshold body, and it prints out correctly, however I still get a validation error, when I'm trying to get my integration test to pass:

{"name":"ValidationError","message":"ValidationError: Validation failed","errors":[{"location":"body","param":"thresholds","value":{"min":3,"max":5},"msg":"Invalid value"}]}

I am relatively new to Express Validator so if I'm chaining the validation wrong/not using oneOf correctly or something would love some pointers!

Thanks


Solution

  • Looks like the .custom function needs to return a Promise. Answer below:

    .custom(innerBody => {
                if (!(innerBody.min) || !(innerBody.max)) return Promise.reject('Missing min or max');
                return Promise.resolve();
            })