Reputation: 2127
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.
Upvotes: 7
Views: 15408
Reputation: 111336
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:
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:
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.
Upvotes: 18
Reputation: 5544
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"})
}
Upvotes: 0