# Express route param regex validation

Recently, I came across some confusion in the [Express 4.x API](http://expressjs.com/4x/api.html) 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`.

![](https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/b8a35112-3076-4e4c-ade5-3c1ca467e7b5.png align="center")

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](https://github.com/strongloop/expressjs.com/issues/388) 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)`](http://expressjs.com/4x/api.html#router.param) method if you're using express `<= 4.11`. (you can use `app` instead of router)

```javascript
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:

```javascript
// 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.

```javascript
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*](http://seanwragg.com/2015/05/26/express-route-param-regex-validation/) *on May 26, 2015.*
