New in Symfony 7.1: MacAddress and Charset Constraints


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

Contributed by Ninos Ego
in #51862 and
#54473.

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:

// 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:

#[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:

// 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:

#[Assert\Charset(['ASCII', 'JIS', 'UTF-8'])]
protected string $content;

Sponsor the Symfony project.