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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With