This is the first article of the series that shows the most important new features introduced by Symfony 7.2, which will be released at the end of November 2024.
Symfony includes tens of constraints to validate data in your applications. In Symfony 7.2 we're adding three new constraints.
Week
Constraint
This constraint validates that a given string (or an object implementing the
Stringable
PHP interface) represents a valid week number according to the
ISO-8601 standard (e.g. 2025-W01
). This is the same format used in the
week HTML input field:
1 2 3 4 5 6 7 8 9 10
// src/Entity/Rental.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Rental
{
#[Assert\Week]
protected string $bookingWeek;
}
This constraint includes the max
and min
options to further restrict
which weeks the user can select:
1 2 3 4 5 6 7 8 9 10
// src/Entity/OnlineCourse.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class OnlineCourse
{
#[Assert\Week(min: '2022-W01', max: '2022-W20')]
protected string $startWeek;
}
Validating whether a week is valid or not is not as trivial as it looks because certain years have 53 weeks instead of the usual 52 weeks. Thanks to this new constraint you can now forget about those details and let Symfony handle the validation logic.
WordCount
Constraint
This constraint validates that a string (or an object implementing the Stringable
PHP interface) contains a number of words that falls in the given min-max range:
1 2 3 4 5 6 7 8 9 10
// src/Entity/BlogPostDTO.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class BlogPostDTO
{
#[Assert\WordCount(min: 100, max: 200)]
protected string $content;
}
Counting words is a difficult problem to solve. That's why this constraint relies
on the IntlBreakIterator class from PHP. This is also heavily dependent on the
content language, so you can use the locale
option to define the locale of the
contents (by default it uses the same as the current application locale).
Yaml
Constraint
Despite its quirks, YAML remains an extremely popular configuration language.
That's why we've added a constraint that checks if the given string (or Stringable
object) contains valid YAML syntax:
1 2 3 4 5 6 7 8 9 10
// src/Entity/Report.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Report
{
#[Assert\Yaml(message: "Your configuration doesn't have valid YAML syntax.")]
private string $customConfiguration;
}
You can also use any of the configuration flags defined in the Symfony Yaml component:
1 2 3 4 5
#[Assert\Yaml(
message: "Your configuration doesn't have valid YAML syntax.",
flags: Yaml::PARSE_CONSTANT | Yaml::PARSE_CUSTOM_TAGS | Yaml::PARSE_DATETIME,
)]
private string $customConfiguration;