Zanko
Zanko

Reputation: 4694

ExpressJS post data validation and enforcing data type

How do I enforce data type for javascript in an "elegant way"? Let's say that on client side a post request of following format is expected,

{
   field1 : 123, //Number
   field2 : "HI", //String
   field3 : {
              subfield1: 1234
              subfield2: "asd"
            }
}

in my express route I would get so paranoid due to the fact that client can send over anything (using console, ajax, or firebug etc.). Hence I would manually validate each field which I find very tedious and tiring. For example,

router.post('/api/add', function (req, res) {
    function validVariable(input) {
        return (typeof input !== 'undefined') && input;
    }
    if (!validVariable (req.body.field1)) {
        res.send("Not Valid");
    }
    if (!validVariable (req.body.field2)) {
        res.send("Not Valid");
    }   
    if (!validVariable (req.body.field3)) {
        res.send("Not Valid");
    }
    //Since everything is valid, time to check type
    if (typeof req.body.field1 != 'Number')) {
        res.send("Not Valid");
    }
    if (typeof req.body.field2 != 'String')) {
        res.send("Not Valid");
    }
    if (typeof req.body.field3 != 'Object')) {
        res.send("Not Valid");
    }
    //and so on...
});

I have to even check the structure of JSON to make sure that the post data is valid in term of structure. After doing this for quite sometimes, I am feeling a little uncomfortable. Can someone please point in the the right direction? Is this way of doing thing a little overkill? Do I really have to worry that much that client can potentially POST any data over?

Upvotes: 3

Views: 1053

Answers (1)

marton
marton

Reputation: 1350

Popular express middleware for request validation and sanitization:
Express validation
Express validator (built on top of node-validator)

I use the latter and I find that the syntax lets me write less code and the middleware structure helps with reusability.

Whether you have to worry that much is on a case by case basis, depends on your security concerns and how informative your errors have to be.

Upvotes: 2

Related Questions