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
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;
Nice improvements :)
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" ^^
@Christophe good catch! It's fixed now. Thanks.
The link to the mb_detect_encoding function fails.
@Antonio you are right! We've just fixed it. Thanks!