Skip to content
Snippets Groups Projects

Add validation to verify email form.

5 unresolved threads
Files
2
+ 20
11
@@ -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.
*/
Please register or sign in to reply
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]));
}
}
/**
Loading