diff --git a/src/Form/VerifyEmailForm.php b/src/Form/VerifyEmailForm.php index 221106c5c625fdb7d36b07454bde191c6bf0de1f..18721ea7419967bfacc739dfb916a8cd8f72fb2e 100644 --- a/src/Form/VerifyEmailForm.php +++ b/src/Form/VerifyEmailForm.php @@ -4,15 +4,29 @@ namespace Drupal\verify_email\Form; +use Drupal\Component\Utility\EmailValidatorInterface; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\verify_email\VerifyEmailInterface; +use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides a Verify Email form. */ final class VerifyEmailForm extends FormBase { + /** + * Constructs a new VerifyEmailForm. + */ + public function __construct(protected EmailValidatorInterface $emailValidator) {} + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container): self { + return new static($container->get('email.validator')); + } + /** * {@inheritdoc} */ @@ -31,7 +45,7 @@ public function buildForm(array $form, FormStateInterface $form_state, VerifyEma '#suffix' => '</div>', ]; - $form['message'] = [ + $form['email'] = [ '#type' => 'textfield', '#title' => $this->t('Enter your email address'), '#required' => TRUE, @@ -52,16 +66,11 @@ public function buildForm(array $form, FormStateInterface $form_state, VerifyEma * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state): void { - // @todo Validate the form here. - // Example: - // @code - // if (mb_strlen($form_state->getValue('message')) < 10) { - // $form_state->setErrorByName( - // 'message', - // $this->t('Message should be at least 10 characters.'), - // ); - // } - // @endcode + // Use the email validator service to validate the email address. + $email = $form_state->getValue('email'); + if (!$this->emailValidator->isValid($email)) { + $form_state->setErrorByName('email', $this->t('The email address %email is not valid.', ['%email' => $email])); + } } /** diff --git a/tests/src/Functional/VerifyEmailRoutingTest.php b/tests/src/Functional/VerifyEmailRoutingTest.php index a36f9e224a62d9784df8fed14a962db95b46998c..a67258550cca3e516a9edd4fea1905c7d57f8109 100644 --- a/tests/src/Functional/VerifyEmailRoutingTest.php +++ b/tests/src/Functional/VerifyEmailRoutingTest.php @@ -59,4 +59,17 @@ public function testVerifyEmailRoute(): void { $this->assertSession()->pageTextContains('Enter your email address.'); } + /** + * Tests invalid email validation. + */ + public function testInvalidEmail(): void { + $this->drupalGet('/verify-email-form'); + $this->assertSession()->statusCodeEquals(200); + // Submit the form with an invalid email address. + $this->submitForm([ + 'email' => 'invalid-email', + ], 'Verify'); + $this->assertSession()->pageTextContains('The email address invalid-email is not valid.'); + } + }