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.
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.