Search code examples
javascriptnode.jsexpressexpress-validator

How to validate the request body if the body is a single json array?


I am trying to validate the body of the request using the express-validator.The hole body is a single array, so i don't have a field name.

I am using the new API of express-validator and express version 4.

The body looks like this:

["item1","item2"]

My code:

app.post('/mars/:Id/Id', [
    check('id')
        .isLength({  max: 10 })

    .body() //try many ways to get the body. most examples i found were for the old api
    .custom((item) => Array.isArray(item))
],
    (req, res, next) => {           
       const data: string = matchedData(req); //using this method to only pass validated data to the business layer
       return controller.mars(data); //id goes in data.id. i expect there should be an data.body once the body is validated too.
    }

How do i validate the body?


Solution

  • If you are using ajax, try to put your array inside an object like the following:

    $.ajax({
        type: "POST",
        url: url,
        data: { arr: ["item1", "item2"] },
        success: function (data) {
            // process data here
        }
    });
    

    Now you could use arr identifier to apply validation rules:

    const { check, body, validationResult } = require('express-validator/check');
    
    ...
    
    app.post('/mars/:Id/Id', [
        check('chatId').isLength({  max: 10 }),
        body('arr').custom((item) => Array.isArray(item))
    ], (req, res, next) => {           
           const data: string = matchedData(req); 
           return controller.mars(data); 
    });