Search code examples
node.jsexpressjoiexpress-validator

Express-validator: How can we validate an Object keys?


I am facing an issue with express-validator to validate an object with two keys. My approach is something like below.

  check('contact.code')
    .trim()
    .isNumeric()
    .withMessage('Country code must be numeric.')
    .bail()
    .isLength({min: 1, max: 4})
    .withMessage('Invalid country code.')
    .bail(),
  check('contact.number')
    .trim()
    .isNumeric()
    .withMessage('Phone number must be numeric.')
    .bail()
    .isLength({max: 10, min: 10})
    .withMessage('Phone number must be 10 digits long.')
    .bail(),

In req.body I'm sending my contact as, contact: {"code": "91", "number":"9087654321"} But I'm getting the error:

{
    "errors": [
        {
            "value": "",
            "msg": "Country code must be numeric.",
            "param": "contact.code",
            "location": "body"
        },
        {
            "value": "",
            "msg": "Phone number must be numeric.",
            "param": "contact.number",
            "location": "body"
        }
    ]
}

I already googled it but didn't get any success. Please help me to solve this issue. Any kind of help will be greatly appreciated.


Solution

  • Setting up the sanitazion/validation check middlewares as follows seems to work fine:

    const validationResult = require('express-validator').validationResult;
    const check = require('express-validator').check;
    
    const express = require('express');
    const app = express();
    app.use(express.json());
    
    app.post('/test-validation',
      [
        check('contact.code')
          .trim()
          .isNumeric()
          .withMessage('Country code must be numeric.')
          .bail()
          .isLength({ min: 1, max: 4 })
          .withMessage('Invalid country code.')
          .bail(),
        check('contact.number')
          .trim()
          .isNumeric()
          .withMessage('Phone number must be numeric.')
          .bail()
          .isLength({ max: 10, min: 10 })
          .withMessage('Phone number must be 10 digits long.')
          .bail(),
      ], (req, res) => {
        const errors = validationResult(req).array();
        if (errors && errors.length) {
          console.log(errors);
          res.status(400).json({ errors });
        } else {
          res.status(201).end();
        }
      });
    
    app.listen(3000, () => console.log(`Server running`));
    

    Here's this code on codesandbox and a sample curl:

    curl --location --request POST 'https://mwjbg.sse.codesandbox.io/test-validation' \
    --header 'Content-Type: application/json' \
    --header 'Accept: application/json' \
    --header 'Cookie: __cfduid=d7012caa5f36c195967d2fc26d3b7bd431595933685' \
    --data-raw '{ "contact": {"code": "1sdf23", "number":"9087654321"}}'
    

    This curl will return:

    {
        "errors": [
            {
                "value": "1sdf23",
                "msg": "Country code must be numeric.",
                "param": "contact.code",
                "location": "body"
            }
        ]
    }