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 AppEntity;

use SymfonyComponentValidatorConstraints as Assert;

class Device
{
// …

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

#[AssertMacAddress(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 AppEntity;

use SymfonyComponentValidatorConstraints as Assert;

class FileDTO
{
// …

#[AssertCharset(‚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:

#[AssertCharset([‚ASCII‘, ‚JIS‘, ‚UTF-8‘])]
protected string $content;

Sponsor the Symfony project.

Symfony Blog

Read More

Latest News

PHP-Releases

PHP 8.3.7 released!

PHP 8.2.19 released!

Generated by Feedzy