1

Let's say I have a post request with body :

{
    "from":"mr.x@example.com",
    "recipient":[
        "john.doe@email.com",
        "ramesh.suresh@example.com",
        "jane.doe"
    ]
}

Here is my request handler :

const { validationResult, body } = require("express-validator");

router.post(
    "/api/request",
    body("from").notEmpty().isEmail(),
    body("recipient").isArray({ min: 1 }),
    (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        res.sendStatus(200)
    }
);

How to do validate whether "recipients" is an array of email ids using express validator? Now I know that isEmail() checks for email and isArray() checks for an Array. How do I combine the 2 to check if it's an "Array of Email Ids"?

Rohit Rane
  • 2,790
  • 6
  • 25
  • 41

1 Answers1

1

You can combine the two checks in the following way, using wildcards:

const { validationResult, body } = require("express-validator");

router.post(
    "/api/request",
    body("from").notEmpty().isEmail(),
    body("recipient").isArray({ min: 1 }),
    body("recipient.*").not().isArray().isEmail(), // Here lies the "magic" :)
    (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        res.sendStatus(200)
    }
);

NOTE: you need the ".not().isArray()" because a nested array of emails would pass the check

Quiquetas
  • 427
  • 7
  • 10