Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

New in Symfony 5.1: Hostname Validator

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

Contributed by
Dmitrii Poddubnyi
in #31518.

Symfony provides tens of validators to check the validity of your data. That includes several validators related to computers and the Internet, such as the email validator, the IP address validator and the URL validator.

In Symfony 5.1 we've added a new one to this group: the Hostname validator, which checks that the given value is considered valid as a hostname:

// src/Entity/ServerSettings.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class ServerSettings
     * @Assert\Hostname(message="The server name must be a valid hostname.")
    protected $name;

The Hostname validator takes into account the top-level domains reserved in the RFC 2606 (, etc.), so you don't have to deal with those special cases. The requirement of including a top-level domain or not is also configurable, as you can read in the docs of this validator.

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.


Can I use this validator with an array of hosts? For example the field can has many value, split by ",".
@Nilmar if you have an array of hosts to validate, you can use the All constraint to apply the Hostname constraint on all values in the array.

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.