Express route param regex validation

Sean Wragg
May 26, 2015 · 2 min read

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 and .

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 method if you're using express . (you can use 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;
} else {

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 ' +;

express 4.12

If you’re using express you can accomplish the same without the need of 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 on May 26, 2015.


Code, Comics, and Fhqwhgads!

Sean Wragg

Written by

Writing about code, comics, and fhqwhgads!



Code, Comics, and Fhqwhgads!