northsideknight
northsideknight

Reputation: 1557

Can you have express middleware check a route-specific config?

I have a node/express project in which for any POST request made, I want to validate the fields in the body of the request.

For this I would like to setup a config per route that handles POST methods, the config would have a list of fields with their constraints, something like this:

router.post('/some_path', function(request, response, next){
    this.fieldsToValidate = [
        {
            name: 'field_name',
            required: true,
            ...
        },
        ...
    ]
    // handle route after validation
}

I would like this to be a per-route configuration, such that I can define a set of fields and their constraints and they will be validated by middleware automatically.

so middleware would look something like:

function(request, response, next){
    if (request.method === 'POST'){
        this.fieldsToValidate.forEach(function(field){
            //do some validation
        });
    }
    next();
}

I understand that middleware is run before the request, but is there any way to have a per-route configuration like this and validate it with middleware?

Thanks in advance.

Upvotes: 1

Views: 1726

Answers (2)

Şivā SankĂr
Şivā SankĂr

Reputation: 2036

express-validator an express.js middleware for node-validator. I'm using on my projects working good. You can do both validation and sanitization.

  // VALIDATION
  // checkBody only checks req.body; none of the other req parameters
  // Similarly checkParams only checks in req.params (URL params) and
  // checkQuery only checks req.query (GET params).
  req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
  req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
  req.checkQuery('getparam', 'Invalid getparam').isInt();

  // OR assert can be used to check on all 3 types of params.
  // req.assert('postparam', 'Invalid postparam').notEmpty().isInt();
  // req.assert('urlparam', 'Invalid urlparam').isAlpha();
  // req.assert('getparam', 'Invalid getparam').isInt();

  // SANITIZATION
  // as with validation these will only validate the corresponding
  // request object
  req.sanitizeBody('postparam').toBoolean();
  req.sanitizeParams('urlparam').toBoolean();
  req.sanitizeQuery('getparam').toBoolean();

Upvotes: 0

TommyLike
TommyLike

Reputation: 1018

How about this one:
use express-validator(check in detail) and route regex to check your parameters,assume that your apis are all in /api/ *:

the server:

var expressValidator = require('express-validator');
app.use(bodyParser.json());
app.use(expressValidator());
app.use('/api',function(req,res,next){
    switch(req.baseUrl)
    {
        case ://API 1
          req.checkHeaders('user','valid header').notEmpty();
          break;
        case ://API 2
        //Others
    }
    var errors = req.validationErrors();
    if (errors) {
        res.send('There have been validation errors: ' + util.inspect(errors), 400);
        return;
    }
    next();
});

Upvotes: 2

Related Questions