Express route param regex validation

Sean Wragg
Sean’s Blog
Published in
2 min readMay 26, 2015

Recently, I came across some confusion in the Express 4.x API documentation regarding how to use regex to validation route parameters. It seems there’s been an update and the method to accomplish this differs from version 4.11 and 4.12.

The punchline here is that the docs actually provide all the information needed but, when you’re glancing for a quick overview in how their API works, it can be very easy to miss (and apparently I’m not the only one who feels that way).

The quick and dirty:

express 4.11

Essentially the following snippet would need to be run prior to leveraging the router.param(fn) method if you're using express <= 4.11. (you can use app instead of router)

router.param(function(name, fn) {  
if (fn instanceof RegExp) {
return function(req, res, next, val) {
var captures;
if (captures = fn.exec(String(val))) {
req.params[name] = captures;
next();
} else {
next('route');
}
}
}
});

This then grants you the ability to validate route params using the following:

// validation rule for id: should be one or more digits
router.param('id', /^\d+$/);

router.get('/user/:id', function(req, res) {
res.send('user ' + req.params.id);
});

express 4.12

If you’re using express >= 4.12 you can accomplish the same without the need of router.param(fn) using the following. In fact, the pre 4.12 example above will pop a deprecation warning.

app.get('/user/:userId([0-9]+)', fn);

While this is stated in the doc, it is quite easy to miss. Hopefully this helps clear things up for those that skim the docs as I did.

Originally published at seanwragg.com on May 26, 2015.

--

--