Search code examples
javascriptnode.jsexpressexpress-validator

Conditionally run check in express-validator


I am trying to conditionally run check in express validator, the functional part of the validator can easily be handled because I am passing in req but the check part won't conditionally run. Please help

I've tried turning the check part to a function and it is not working. This is what I want to achieve but the tenary fails

const onewayCheck = body('tripType').equals('one-way') ? [
  body('currentOfficeLocation')
    .exists({ checkFalsy: true })
    .withMessage('currentOfficeLocation Current Office Location is required')
    .isInt()
    .withMessage('currentOfficeLocation Current Office Location must be an integer'),
  body('destination')
    .exists({ checkFalsy: true })
    .withMessage('destination Destination is required')
    .isInt()
    .withMessage('destination Destination must be an integer'),
  body('departureDate')
    .exists({ checkFalsy: true })
    .withMessage('departureDate Departure date is required'),
  body('travelreasons')
    .exists({ checkFalsy: true })
    .withMessage('travelReasons Travel Reasons is required')
    .isString()
    .withMessage('travelReasons Travel Reasons should be strings'),
  body('accommodation')
    .exists({ checkFalsy: true })
    .withMessage('accommodation Accommodation is required')
    .isInt()
    .withMessage('accommodation Accommodation must be an integer'),
] : [];

I want to ensure the check woks


Solution

  • I was able to solve it by using a middleware in the route as follows

    
    router
      .post('/request', validate(onewayCheck(), 'one-way'),
        onewayValidateInput,
        validate(multicityCheck(), 'Multi-city'), multicityValidateInput, tripRequest)
    
    

    The validate function checks for the type of request

    
    const validate = (validations, tripType) => async (req, res, next) => {
      if (req.body.tripType === tripType) {
        await Promise.all(validations.map(validation => validation.run(req)));
      }
      return next();
    };