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

Raffaele Carelle
Contributed by Raffaele Carelle in #58542

In web development, a slug is a user-friendly, URL-safe string created from a title or name and used to identify a resource in a web address. It typically contains only lowercase letters and numbers, with other characters replaced by hyphens. In Symfony 7.3, you can apply the new Slug constraint to any property that should act as a slug to validate its contents:

1
2
3
4
5
6
7
8
9
10
11
12
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Category
{
    #[Assert\Slug]
    protected string $slug;

    // ...
}

If the category name is, for example, Top Sellers and you create its slug as top-sellers, the validation will pass. However, a value like top sellers or top_sellers will fail. The regular expression used by the constraint is /^[a-z0-9]+(?:-[a-z0-9]+)*$/.

You can customize this regular expression with the regex option, but if you need significant changes, it's better to use the Regex constraint instead.

Twig Constraint

Mokhtar Tlili
Contributed by Mokhtar Tlili in #58805

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;
Published in #Living on the edge