Require Route Parameter To Start With @ To Match

In This Snippet

You can use route matchers to specify requirements on the route parameter. In this snippet, we require our username param to start with the @ character for the route to match.

Created by
@tomgobich
Published

Route parameter matchers give you the ability to enforce requirements upon the parameter in order for a given route to match a request.

If you'd like to learn more about route parameters and their matchers, check out our lesson "Dynamic Routing with Route Parameters".

Username Snippet

In the below snippet, the route parameter matcher (defined by the where method) is restricting this profiles.show route to only match if the username param specifically begins with @.

/@adocasts matches route
/adocasts does not match

Route.get('/:username', 'ProfilesController.show')
  .as('profiles.show')
  .where('username', /^@/)
Copied!
  • start
  • routes.ts

Purpose

By forcing our username param to start with @, we're able to simplify our profiles.show route, while still making use of other /something routes within our application.

For example:

// will only match if username starts with @
// if username does NOT start with @, this route will be bypassed
Route.get('/:username', 'ProfilesController.show')
  .as('profiles.show')
  .where('username', /^@/)

// when the previous route is bypassed, it'll be used to match this route
Route.get('/:slug', 'PostsController.show').as('posts.show')
Copied!
  • start
  • routes.ts

Join the Discussion 0 comments

Create a free account to join in on the discussion
robot comment bubble

Be the first to comment!