You are here

public function LearningPathCreateUserForm::validateForm in Opigno Learning path 8

Same name and namespace in other branches
  1. 3.x src/Form/LearningPathCreateUserForm.php \Drupal\opigno_learning_path\Form\LearningPathCreateUserForm::validateForm()

Form validation handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormBase::validateForm

File

src/Form/LearningPathCreateUserForm.php, line 66

Class

LearningPathCreateUserForm
Members create form.

Namespace

Drupal\opigno_learning_path\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {

  // Validate empty user name.
  if (empty($form_state
    ->getValue('name'))) {
    $form_state
      ->setErrorByName('name', $this
      ->t('User name is required.'));
  }
  else {
    $others = $this
      ->entityTypeManager()
      ->getStorage('user')
      ->loadByProperties([
      'name' => $form_state
        ->getValue('name'),
    ]);

    // Validate used user name.
    if (count($others) > 0) {
      $form_state
        ->setErrorByName('name', $this
        ->t('The user name is in use, please enter another name.'));
    }
  }
  $email = $form_state
    ->getValue('email');

  // Validate empty user email.
  if (empty($email)) {
    $form_state
      ->setErrorByName('email', $this
      ->t('User email is required.'));
  }
  else {
    $validator = new EmailValidator();
    if (!$validator
      ->isValid($email)) {
      $form_state
        ->setErrorByName('email', $this
        ->t('Invalid email'));
    }
    else {
      $others = $this
        ->entityTypeManager()
        ->getStorage('user')
        ->loadByProperties([
        'mail' => $email,
      ]);

      // Validate used user email.
      if (count($others) > 0) {
        $form_state
          ->setErrorByName('email', $this
          ->t('The email is in use, please enter another email.'));
      }
    }
  }
}