Validate route parameters

Last updated on
31 October 2024

This documentation needs review. See "Help improve this page" in the sidebar.

Pattern validation

Drupal's routes placeholder values (i.e., parameters passed in the URL) may be validated using the routing system. Placeholder values could be of type string, integer, or any pattern that can be validated with a regular expression. If validation of the parameters fails, then a page not found is returned.

We can define constraints for the values of the placeholders as regular expressions.
For example in example.routing.yml:
{name} placeholder should string and contains only uppercase and lowercase alphabet.

example.user
  path: '/example/{name}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'access content'
    name: '[a-zA-Z]+'

If validation fails, a 404 Response will be issued. If you want to respond with another HTTP response, you cannot use this form of validation and will need to implement your own within your controller.

Access validation

The route's '_entity_access' requirement must follow the pattern 'slug.operation'. Typically, the slug is an entity type ID, but it can be any slug defined in the route. The route match parameter corresponding to the slug is checked to see if it is entity-like, that is: implements EntityInterface. Available operations are: 'view', 'update', 'create', and 'delete'.

For example, this route configuration invokes a permissions check for 'update' access to entities of type 'node':

example.route:
  path: '/foo/{node}/bar'
  requirements:
    _entity_access: 'node.update'

And this will check 'delete' access to a dynamic entity type:

example.route:
  path: '/foo/{entity_type}/{example}'
  requirements:
    _entity_access: example.delete
  options:
    parameters:
      example:
        type: entity:{entity_type}

Help improve this page

Page status: Needs review

You can: