New in Symfony 7.1: MacAddress and Charset Constraints
May 8, 2024 • Published by Javier Eguiluz
Symfony 7.1 is backed by:
Symfony provides tens of validation constraints to perform any kind of validation on your data. In Symfony 7.1 we're expanding that list with two new constraints.
MacAddress Constraint
This constraint ensures that the given value is a valid MAC address. Internally,
it uses the FILTER_VALIDATE_MAC
option of the filter_var PHP
function. Use this whenever you need to check a property of this type:
1 2 3 4 5 6 7 8 9 10 11 12
// src/Entity/Device.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Device
{
// ...
#[Assert\MacAddress]
protected string $mac;
}
By default, all types of MAC addresses are considered valid, but you can use the
type
option to restrict which kind of MAC addresses you want to consider valid:
1 2
#[Assert\MacAddress(type: 'local_no_broadcast')]
protected string $mac;
Read the MacAddress constraint docs to learn about all the types available.
Charset Constraint
Contributed by
Alexandre Daubois
in #53154.
This new constraint ensures that a given string (or Stringable
object) is
encoded in a specified charset. This is useful, for example, when working with
DTOs that contain file data and you need to verify that this data is encoded in
a specific charset, such as UTF-8:
1 2 3 4 5 6 7 8 9 10 11 12
// src/Entity/FileDto.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class FileDto
{
// ...
#[Assert\Charset('UTF-8')]
protected string $content;
}
You can accept more than one charset and their possible values are the same as the ones used in the mb_detect_encoding PHP function:
1 2
#[Assert\Charset(['ASCII', 'JIS', 'UTF-8'])]
protected string $content;
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
A little typo in the snippet of the MAC constraint, the first line should be "// src/Entity/Device.php" instead of "// src/Entity/Author.php" ^^