New in Symfony 5.1: Hostname Validator
March 19, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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:
1 2 3 4 5 6 7 8 9 10 11 12
// 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 (.example.com
, 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.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Can I use this validator with an array of hosts? For example the field can has many value, split by ",".
Awesome!!
@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.