Home » Nodejs » POST Data JSON Validation in Express.js

POST Data JSON Validation in Express.js

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’m writing an app using Node.js and Express.js. The app has a (small) REST API and then a web front end. I use MongoDb.

For the API, I tend POST data to some endpoint and then do processing or whatever, and dump it in a database. However, I have some database schema I would like to enforce. What are my options / best practices for enforcing a specific structure on my POST data so I know that certain fields are present and of specific types.

It would be nice if this could be done at the middleware level, but it isn’t necessary. What do people usually do for validation / schema enforcement?

Answers:

node-validator is what you are looking for. You can use it as a standalone module like this

var check = require('validator').check;

//Validate
check('[email protected]').len(6, 64).isEmail();        //Methods are chainable
check('abc').isInt();                                //Throws 'Invalid integer'

Or you can use express-validator which is built on top of node-validator as a middleware.

Questions:
Answers:

Here is a more recent benchmark of various JSON schema validators.

Also, for best practices you may want to check out JSON-schema which attempts to lay out a standard way of defining how a JSON object should be defined.