The Validator component provides dozens of constraints ready to use in your applications. In Symfony 7.3, we've added two new constraints to the list.
Slug Constraint
Update: The Slug
constraint was removed after the second beta of
Symfony 7.3. We made this decision because there's no formal specification
for slugs, so they can take many forms (e.g. only lowercase or mixed case,
allowing or forbidding starting with a number, etc.).
Instead of providing a lot of configurable options, it's better to customize the regular expression used to validate slugs. In that case, you should better use the existing Regex constraint instead. Here's how to validate slug contents with it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// this replicates the default behavior of the now-deleted Slug constraint
#[Assert\Regex('/^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$/')]
private string $slug;
// to only allow lowercase letters
#[Assert\Regex('/^[a-z0-9]+(?:-[a-z0-9]+)*$/')]
private string $slug;
// to disallow slugs starting with a number
#[Assert\Regex('/^[a-z](?:[a-z0-9]+)?(?:-[a-z0-9]+)*$/')]
private string $slug;
// reusing the regexp from the routing component
use Symfony\Component\Routing\Requirement\Requirement;
#[Regex('/^'.Requirement::ASCII_SLUG.'$/')]
private string $slug;
Twig Constraint
Symfony includes Json constraint and Yaml constraint to validate that a given text content is valid according to those formats. In Symfony 7.3, we're adding Twig to the list of formats and syntaxes that can be validated:
1 2 3 4 5 6 7 8 9
use Symfony\Bridge\Twig\Validator\Constraints\Twig;
class Template
{
#[Twig]
private string $templateCode;
// ...
}
The Twig
constraint validates that the given content can be correctly parsed
as a Twig template. By default, deprecations are ignored during validation.
If you want stricter validation that fails when any deprecation is detected, use
the following option:
1 2
#[Twig(skipDeprecations: false)]
private string $templateCode;
I get it why the slug constraint was removed. Thank you for the examples on how we can implement it ourselves.
Line 13 of the slug constraint examples misspells "routing."
@Eric fixed the typo! Thanks.