Validating POST Params with Express-Validator

Anconia picture Anconia · Jun 14, 2014 · Viewed 9.1k times · Source

I'm trying to build parameter validation into my Node/Express API using express-validator. However, when I make a POST request with a missing field (name in this case) using the following curl command curl -X POST -d "foo=bar" http://localhost:3000/collections/test, the request still goes through successfully, skipping the validation. Below is my current code - any ideas as to why the validation is bypassed?

var util = require('util');
var express = require('express');
var mongoskin = require('mongoskin');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');

var app = express();
app.use(bodyParser());
app.use(expressValidator());

var db = mongoskin.db('mongodb://@localhost:27017/test', {safe:true})

app.param('collectionName', function(req, res, next, collectionName){
  req.collection = db.collection(collectionName)
  return next()
});

app.post('/collections/:collectionName', function(req, res, next) {
  req.checkBody('name', 'name is required').notEmpty();

  req.collection.insert(req.body, {}, function(e, results){
    if (e) return next(e)
    res.send(results)
  });
});

app.listen(3000);

Answer

dylants picture dylants · Jun 14, 2014

You need to add a check for any validation errors prior to processing the request. So for your post API you'll need to update it to look something like:

app.post('/collections/:collectionName', function(req, res, next) {
  req.checkBody('name', 'name is required').notEmpty();

  // check for errors!
  var errors = req.validationErrors();
  if (errors) {
    res.send('There have been validation errors: ' + util.inspect(errors), 400);
    return;
  }

  req.collection.insert(req.body, {}, function(e, results){
    if (e) return next(e)
    res.send(results)
  });
});

For more information, see the usage example: https://github.com/ctavan/express-validator#usage