How can I restrict external URLs in link field to allow only certain domains? After creating a Link field and use the Link with service icon format, I find out that there is no option to restrict external URLs to external domains that I want
For example, if I only want to allow Twitter links, something like add https://www.twitter.com/*.
Someone already asked here, but it seems that the Advanced Link module is not available for my Drupal version.
With what module and how can I filter my desired URLs in Drupal 9?
You need to write your own custom validation contraint and add this constraint to your field.
Docs: https://www.drupal.org/docs/drupal-apis/entity-api/entity-validation-api/providing-a-custom-validation-constraint
I've used that example to create a &quot;force HTTPS&quot; link field constraint
src/Plugin/Validation/Constraint/Https.php
&lt;?php

namespace Drupal\MYMODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that the submitted URL is starting with https://
 *
 * @Constraint(
 *   id = &quot;MY_CONSTRAINT_ID&quot;,
 *   label = @Translation(&quot;Https&quot;, context = &quot;Validation&quot;),
 *   type = &quot;string&quot;
 * )
 */
class Https extends Constraint {
  public $notHttps = '%uri is not a secure site (not starting with https://)';
}

src/Plugin/Validation/Constraint/HttpsValidator.php
&lt;?php

namespace Drupal\MYMODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the Https constraint.
 */
class HttpsValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    $item = $items-&gt;first();
    if (!isset($item)) {
      return NULL;
    }

    foreach ($items as $item) {
      /* CHANGE THIS, e.g. here you can check for domain names */
      if (strpos($item-&gt;uri, 'https://') !== 0) {
        $this-&gt;context-&gt;addViolation($constraint-&gt;notHttps, ['%uri' =&gt; $item-&gt;uri]);
      }
    }
  }
}

MYMODULE.module
&lt;?php

use Drupal\Core\Entity\EntityTypeInterface;

function MYMODULE_entity_bundle_field_info_alter(&amp;$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($bundle === 'MY_ENTITY_BUNDLE' &amp;&amp; $entity_type-&gt;id() == 'MY_ENTITY_TYPE') {
    if (isset($fields['MY_FIELD'])) {
      $fields['MY_FIELD']-&gt;addConstraint('MY_CONSTRAINT_ID', []);
    }
  }
}