Stop writing the same regex for #[Route]
Stiven Llupa

Stiven Llupa @stivenllupa

Joined:
Feb 24, 2026

Stop writing the same regex for #[Route]

Publish Date: Feb 27
8 2

Did you know Symfony ships with a built-in class full of pre-defined route requirement patterns?

It's called Requirement, and it lives in Symfony\Component\Routing\Requirement.

Instead of writing your own regex for common route parameters like UUIDs, slugs, date formats, or locale codes, you can just reference a constant.

So instead of this mess in your route attribute:

#[Route('/users/{id}', requirements: [
    'id' => '[0-9a-f]{8}-[0-9a-f]{4}-'
          . '[0-9a-f]{4}-[0-9a-f]{4}-'
          . '[0-9a-f]{12}',
])]
public function show(string $id): Response
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

You write:

#[Route('/users/{id}', requirements: [
    'id' => Requirement::UUID,
])]
public function show(string $id): Response
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Instead of:

#[Route('/blog/{slug}', requirements: [
    'slug' => '[a-z0-9]+(?:-[a-z0-9]+)*',
])]
public function post(string $slug): Response
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

You write:

#[Route('/blog/{slug}', requirements: [
    'slug' => Requirement::ASCII_SLUG,
])]
public function post(string $slug): Response
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

It includes constants for all UUID formats, common date, ASCII slugs, and your usual suspects.

Stop rewriting the same regex. Symfony already did it for you.

Watch it on YouTube

Comments 2 total

Add comment