最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node JS POST | PUT body validation - Stack Overflow

programmeradmin2浏览0评论

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
  • 1 Depends on what you're validating. There are libraries that can help you with this, like joi – Vsevolod Goloviznin Commented Mar 28, 2017 at 16:17
Add a comment  | 

2 Answers 2

Reset to default 18

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.

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"})
}
发布评论

评论列表(0)

  1. 暂无评论