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.
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.
Share Improve this question asked Mar 28, 2017 at 16:14 Steven BayerSteven Bayer 2,1274 gold badges16 silver badges18 bronze badges 1 |2 Answers
Reset to default 18You 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.
in production level environnement, it's common to see validation steps as middlewares (using Express), and, in general cases, people use validation library or custom modules to match pattern or check objects, so it often looks like the following :
import myValidation from '../helpers/validation';
const validateUserBody = (req, res, next) => {
return myValidation(req.body)
? next()
: res.status(400).json({message: "Bad body"})
}
joi
– Vsevolod Goloviznin Commented Mar 28, 2017 at 16:17