alexmingoia/koa-router — pull request #58 by cristiangraz (2014-03-20 19:37:32+00:00)
Title: Add new validate() method to validate params of a non-regex route and still provide named ctx.params

This adds a new validate() method to the koa-router that allows you to validate a named route parameters with regexes, and still have ctx.params populated with named parameters.

Currently you can only provide a non regex route, i.e.
```
'/articles/:id'
```
or a regex route
```
/\/articles\/([0-9]+)/
```
The problem with the regex route is
1) it's more difficult to read as the route gets longer
2) It's more complex if you only need to validate a single named parameter
3) You don't get the named parameters in ctx.params. Instead of ctx.params.id, you'll get ctx.params[0]

With this pull request, you can do the following:
```
app.get('articles_find', '/articles/:id/:name', function *(next) {
// middleware
}).validate('articles_find', { id: '[0-9]+', name: '[a-z]+' });
```
So that given the following request: /articles/10/john

You will receive
```
ctx.params = {
id: 10,
name: 'john'
}
```

You can optionally validate only the id param or only the name param. The only requirement is that any routes you choose to validate have names.

I decided to create a validate() method to avoid the existing method signature from getting too complex since some variables are optional and not everyone will want this functionality. I'm happy to rework or adjust if someone has a better way to approach this.