9

How do I enforce a requirement that a paramater in a route be a string?

Given the route

my_foobar_route: url: /example/routing/:s1/:id requirements: { id: \d+ }

Can anyone remind me of how to force param s1 to be a string?

morpheous
  • 16,270
  • 32
  • 89
  • 120

3 Answers3

13

You just need to supply a suitable regular expression:

my_foobar_route:
  url: /example/routing/:s1/:id
  requirements:
    id: \d+
    s1: "[a-zA-Z]+"

Edit: Added quotation marks around the second regular expression; YAML interprets [...] as being an array of parameters. Thanks @chiborg :-)

Community
  • 1
  • 1
richsage
  • 26,912
  • 8
  • 58
  • 65
  • Edited, thanks. Always forget about the `[]` being interpreted as a YAML array, my usual regular expressions in routing nearly always end up being `\d+` ;-) – richsage May 26 '11 at 09:21
5

If you don't care what the string contains or if you don't know beforehand what it will contain, try the following:

my_foobar_route:
  url: /example/routing/:s1/:id
  requirements:
    id: \d+
    s1: "[^/]+"

This will allow all characters except the '/' character which is used as a separator for the parameters. With the expression

my_foobar_route:
  url: /example/routing/:s1/:id
  requirements:
    id: \d+
    s1: "[^/]{3,}"

you could force the string to be at least three characters long.

Don't forget to put Regexes with square brackets in quotes! If you forget them, the YAML parser for the routes will interpret them as an array expression.

chiborg
  • 26,978
  • 14
  • 97
  • 115
0

Pretty much anything that comes via the url is a string - any requirement is stronger than this, you you do not need to do anything, your parameter is already a string. Maybe you want a specially formatted string?

Maerlyn
  • 33,687
  • 18
  • 94
  • 85