Skip to content

Commit

Permalink
SHS-5954: Social Media Footer block — allow mailto: links (#1706)
Browse files Browse the repository at this point in the history
* feat(SHS-5954): Allow mailto links for social media block

* refactor(SHS-5954): Change validation to use Drupal core validateUrl

* refactor(SHS-5954): Minor changes from SWS

---------

Co-authored-by: ahughes3 <[email protected]>
  • Loading branch information
codechefmarc and ahughes3 authored Jan 14, 2025
1 parent 0d41267 commit beb82ac
Showing 1 changed file with 29 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\Element\Url;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;
Expand Down Expand Up @@ -126,10 +127,13 @@ public function blockForm($form, FormStateInterface $form_state): array {
$form['links'][$key] = [
'#type' => 'container',
'link_url' => [
'#type' => 'url',
'#type' => 'textfield',
'#title' => $this->t('URL'),
'#description' => $this->t('Social Media Profile URL.'),
'#description' => $this->t('Social Media Profile URL. Must start with https:// or mailto:'),
'#default_value' => $link['link_url'],
'#element_validate' => [
[get_class($this), 'validateUrl'],
],
],
'link_title' => [
'#type' => 'textfield',
Expand Down Expand Up @@ -162,6 +166,29 @@ public function blockForm($form, FormStateInterface $form_state): array {
return $form;
}

/**
* Custom validation for the link_url field.
*/
public static function validateUrl(array &$element, FormStateInterface $form_state, array &$complete_form) {
$value = $element['#value'];

if (empty($value)) {
return;
}

$mailto_regex = '/^mailto:[\w.%+-]+@[A-Za-z0-9-]+\.[A-Za-z]{2,}(?:\?[^\s]*)?$/i';

if (str_starts_with($value, 'mailto')) {
if (!preg_match($mailto_regex, $value)) {
$form_state->setError($element, t('The mailto link must include a valid email address (e.g., mailto:[email protected]).'));
}
return;
}

URL::validateUrl($element, $form_state, $complete_form);

}

/**
* {@inheritdoc}
*/
Expand Down

0 comments on commit beb82ac

Please sign in to comment.