Search code examples
node.jsexpressexpress-validatorexpress-router

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


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

{
    "from":"[email protected]",
    "recipient":[
        "[email protected]",
        "[email protected]",
        "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