You are here

function domain_registration_user_register_validate in Restrict Domain Registration 8

Same name and namespace in other branches
  1. 7 domain_registration.module \domain_registration_user_register_validate()

Custom validation function.

Checks if the domain in the email address is on a list of allowed domains.

1 string reference to 'domain_registration_user_register_validate'
domain_registration_form_user_register_form_alter in ./domain_registration.module
Implements hook_form_form_id_form_alter().

File

./domain_registration.module, line 23
Domain Registration module file.

Code

function domain_registration_user_register_validate(&$form, &$form_state) {

  // Ignore validation if mail already has an error.
  $errors = $form_state
    ->getErrors();
  if (!empty($errors['mail'])) {
    return;
  }
  $mail = explode('@', $form_state
    ->getValue('mail'));
  $domains = \Drupal::service('domain_registration.pattern')
    ->getPatterns();

  // Only attempt to validate if we have a list of domains.
  if ($domains) {

    // Determine if we have matches.
    $match = count(array_filter($domains, function ($domain) use (&$mail) {
      return domain_registration_wildcard_match($domain, $mail[1]);
    }));
    switch (\Drupal::config('domain_registration.settings')
      ->get('method')) {

      // Allow only domains listed to register.
      case DOMAIN_REGISTRATION_ALLOW:
        if (!$match) {
          $form_state
            ->setErrorByName('account', \Drupal::config('domain_registration.settings')
            ->get('message'));
        }
        break;

      // Prevent domains listed from registering.
      case DOMAIN_REGISTRATION_DENY:
        if ($match) {
          $form_state
            ->setErrorByName('account', \Drupal::config('domain_registration.settings')
            ->get('message'));
        }
        break;
    }
  }
}