Bilal El Mahdaoui
Bilal El Mahdaoui

Reputation: 204

express-validator body conditional validation (param)

I have an express route and I want to use it for three different cases. The logic is the same, there are just some minor modifications so I didn't want to create separate endpoints. I used the parameter 'type' to differentiate the cases.

The problem is that I only want to use the second validator when the param type equals to 'twoemails' and I don't know how to do it. I tried using oneOf & anyOf but it didn't seem to work. Thank you!

myRoute.post('/myendpoint/:type',
  param('type', 'Invalid type').isIn(['oneemail', '**twoemails**']),
  body('email1', 'first email invalid').isEmail(),
  body('email2', 'second email invalid').isEmail(),
  async (req, res) => {
      const errors = validationResult(req);

      if (!errors.isEmpty()) {
        return res.status(400).json({
          errors: errors.array(),

        });
      }
...

Upvotes: 1

Views: 3202

Answers (1)

supertux
supertux

Reputation: 2189

You can replace body('email2', 'second email invalid').isEmail() with this:

body('email2')
  .if(param('type').equals('twoemails'))
  .isEmail()
  .withMessage('second email invalid')

And it will only validate the second email if the type is set to twoemails. This relies on your param line been like this, without the *s.

param('type', 'Invalid type').isIn(['oneemail', 'twoemails'])

So the whole solution

myRoute.post('/myendpoint/:type',
  param('type', 'Invalid type').isIn(['oneemail', 'twoemails']),
  body('email1', 'first email invalid').isEmail(),
  body('email2')
    .if(param('type').equals('twoemails'))
    .isEmail()
    .withMessage('second email invalid'),
  async (req, res) => {
      const errors = validationResult(req);

      if (!errors.isEmpty()) {
        return res.status(400).json({
          errors: errors.array(),

        });
      }
...

Upvotes: 2

Related Questions