Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS POST | PUT body validation

In production level environments what is more or less the standard for POST / PUT body validation?

My approach has always been something like:

const isValid = (req.body.foo && /[a-z0-9]*/i.test(req.body.foo))

Only checking that the variable exists and does not contain unexpected characters.

like image 944
Steven Bayer Avatar asked Mar 28 '17 16:03

Steven Bayer


1 Answers

You tagged your question with Express so I'll focus on request body validation in Express. For Express there are two modules used for validation that are most popular:

  • https://www.npmjs.com/package/express-validator
  • https://www.npmjs.com/package/express-validation

Both are stable and widely used. You can use any of them depending on which validation syntax you prefer. The first one is internally using validator. The second one is internally using joi.

See:

  • https://www.npmjs.com/package/validator
  • https://www.npmjs.com/package/joi

Example of express-validator usage inside of a route handler:

req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
req.checkQuery('getparam', 'Invalid getparam').isInt();

Example of express-validation usage as a middleware

validate({body: {
  email: Joi.string().email().required(),
  password: Joi.string().regex(/[a-zA-Z0-9]{3,30}/).required()
}})

This returns a middleware. That object is often exported as a module and stored in a different file.

like image 128
rsp Avatar answered Sep 18 '22 23:09

rsp