Express Req.Body Validation Express Req.Body Validation express express

Express Req.Body Validation


Using JSON schema

Without knowing any more about the specific things you'd like to check for, I think tools based on JSON schema could serve you pretty well. JSON schema specifies many kinds of validation rules.

Examples of node modules:

I made this list based on a simple search for "json schema" on Nipster. I find Nipster is a great tool to get a quick overview of good modules for a particular task because it also includes number of forks and github stars of the project as a gauge for popularity, which in turn often says something about a module's quality and maturity. Of course not to be taken blindly, but as a start for further research.

I expect that actual not all modules for JSON schema have support for all validation rules, so I think you should start by inventorying what kind of rules you actually need (or would like to have available in the future), then narrow down your selection based on that.

There's an official test suite for JSON schema tools. You may want to look for modules that advertise compliance with this suite.

Not using JSON schema


You may want to use a pattern like this:

function validateRegForm(req, res, next){  console.log('Validating form...');  if(!req.body.password){    return res.send(500, 'Need a password');  };  next();};app.post('/regForm', validateRegForm, function(req,res){  // If Express calls this fn, the previous fn did next(), not res.send()  console.log('Doing something with this valid form');  res.redirect('/regForm/complete');});


I know this is old, but for those of you looking for a great way to validate incoming request bodies, as well as headers, route params, and query parameters, check out https://github.com/continuationlabs/celebrate.

It leverages Joi to validate arguments which has a declarative way to reuse and extend validation rules.