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

sean3z

Code, Comics, and Fhqwhgads!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store