express-validator : How to check for an Array of Email IDs?

0

Issue

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"?

Solution

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

Answered By – Quiquetas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More