Example #1
1
 /**
  * Form element validation handler for 'name' in form_test_validate_form().
  */
 public function validateName(&$element, FormStateInterface $form_state)
 {
     $triggered = FALSE;
     if ($form_state->getValue('name') == 'element_validate') {
         // Alter the form element.
         $element['#value'] = '#value changed by #element_validate';
         // Alter the submitted value in $form_state.
         $form_state->setValueForElement($element, 'value changed by setValueForElement() in #element_validate');
         $triggered = TRUE;
     }
     if ($form_state->getValue('name') == 'element_validate_access') {
         $form_state->set('form_test_name', $form_state->getValue('name'));
         // Alter the form element.
         $element['#access'] = FALSE;
         $triggered = TRUE;
     } elseif ($form_state->has('form_test_name')) {
         // To simplify this test, just take over the element's value into $form_state.
         $form_state->setValueForElement($element, $form_state->get('form_test_name'));
         $triggered = TRUE;
     }
     if ($triggered) {
         // Output the element's value from $form_state.
         drupal_set_message(t('@label value: @value', array('@label' => $element['#title'], '@value' => $form_state->getValue('name'))));
         // Trigger a form validation error to see our changes.
         $form_state->setErrorByName('');
     }
 }
Example #2
0
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $cors_domains = $form_state->getValue('cors_domains', '');
     if (empty($cors_domains) && $cors_domains != $form['cors_domains']['#default_value']) {
         $form_state->setErrorByName('cors_domains', t('No domains provided.'));
         return;
     }
     $domains = explode("\r\n", $cors_domains);
     $settings = array();
     $errors = null;
     foreach ($domains as $domain) {
         if (empty($domain)) {
             continue;
         }
         $domain = explode("|", $domain, 2);
         if (empty($domain[0]) || empty($domain[1])) {
             $form_state->setErrorByName('cors_domains', t('Contains malformed entry.'));
             $errors = true;
         } else {
             $settings[$domain[0]] = isset($settings[$domain[0]]) ? $settings[$domain[0]] . ' ' : '';
             $settings[$domain[0]] .= trim($domain[1]);
         }
     }
     if ($settings && !$errors) {
         $form_state->setValue('settings', $settings);
     }
 }
 /**
  * Implements \Drupal\Core\Form\FormInterface::validateForm().
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $error = array();
     $sf_library = preg_replace("/(^[\r\n]*|[\r\n]+)[\\s\t]*[\r\n]+/", "\n", trim($form_state->getValue('superfish_library')));
     if (empty($sf_library)) {
         $form_state->setErrorByName('superfish_library', t('Path to Superfish library field cannot be empty. Please try this list:') . str_replace("\r\n", ",", $this->superfish_library_path()));
     } else {
         // Trimming blank lines and such
         $sf_library = explode("\n", $sf_library);
         // Crystal clear
         foreach ($sf_library as $s) {
             if (!file_exists($s)) {
                 $error[] = $s;
             }
         }
         if (!empty($error)) {
             $error_message = '';
             if (count($error) > 1) {
                 foreach ($error as $e) {
                     $error_message .= '<li>' . $e . '</li>';
                 }
                 $error_message = t('Files not found') . ': <ul>' . $error_message . '</ul>';
             } else {
                 $error_message = t('File not found') . ': ' . $error[0];
             }
             $form_state->setErrorByName('superfish_library', $error_message);
         }
     }
     parent::validateForm($form, $form_state);
 }
 /**
  * Implements \Drupal\Core\Form\FormInterface::validateForm().
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $form_state->set('notify_emails', []);
     if (!$form_state->isValueEmpty('update_notify_emails')) {
         $valid = array();
         $invalid = array();
         foreach (explode("\n", trim($form_state->getValue('update_notify_emails'))) as $email) {
             $email = trim($email);
             if (!empty($email)) {
                 if (valid_email_address($email)) {
                     $valid[] = $email;
                 } else {
                     $invalid[] = $email;
                 }
             }
         }
         if (empty($invalid)) {
             $form_state->set('notify_emails', $valid);
         } elseif (count($invalid) == 1) {
             $form_state->setErrorByName('update_notify_emails', $this->t('%email is not a valid email address.', array('%email' => reset($invalid))));
         } else {
             $form_state->setErrorByName('update_notify_emails', $this->t('%emails are not valid email addresses.', array('%emails' => implode(', ', $invalid))));
         }
     }
     parent::validateForm($form, $form_state);
 }
Example #5
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $file_upload = $this->getRequest()->files->get('files[import_tarball]', NULL, TRUE);
     $has_upload = FALSE;
     if ($file_upload && $file_upload->isValid()) {
         // The sync directory must be empty if we are doing an upload.
         $form_state->setValue('import_tarball', $file_upload->getRealPath());
         $has_upload = TRUE;
     }
     $sync_directory = $form_state->getValue('sync_directory');
     // If we've customised the sync directory ensure its good to go.
     if ($sync_directory != config_get_config_directory(CONFIG_SYNC_DIRECTORY)) {
         // Ensure it exists and is writeable.
         if (!file_prepare_directory($sync_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
             $form_state->setErrorByName('sync_directory', t('The directory %directory could not be created or could not be made writable. To proceed with the installation, either create the directory and modify its permissions manually or ensure that the installer has the permissions to create it automatically. For more information, see the <a href="@handbook_url">online handbook</a>.', array('%directory' => $sync_directory, '@handbook_url' => 'http://drupal.org/server-permissions')));
         }
     }
     // If no tarball ensure we have files.
     if (!$form_state->hasAnyErrors() && !$has_upload) {
         $sync = new FileStorage($sync_directory);
         if (count($sync->listAll()) === 0) {
             $form_state->setErrorByName('sync_directory', t('No file upload provided and the sync directory is empty'));
         }
     }
 }
Example #6
0
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if ($form_state->getValue('cosign_allow_anons_on_https') == 0 && $form_state->getValue('cosign_allow_cosign_anons') == 1) {
         $form_state->setErrorByName('cosign_allow_anons_on_https', $this->t("Cosign users cannot browse anonymously if Anonymous users can't. Set Allow Anonymous Users to browse over https to Yes. OR"));
         $form_state->setErrorByName('cosign_allow_cosign_anons', $this->t("Cosign users cannot browse anonymously if Anonymous users can't. Set Allow Cosign Users to browse anonymously to No."));
     }
 }
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (strlen($form_state->getValue('title')) < 3) {
         $form_state->setErrorByName('title', $this->t('Your name is too short.'));
     }
     if (!UrlHelper::isValid($form_state->getValue('video'), TRUE)) {
         $form_state->setErrorByName('video', $this->t("The video url '%url' is invalid.", array('%url' => $form_state->getValue('video'))));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (strlen($form_state->getValue('title')) == '') {
         $form_state->setErrorByName('title', $this->t('Please enter title.'));
     }
     if (strlen($form_state->getValue('details')) == '') {
         $form_state->setErrorByName('details', $this->t('Please enter details.'));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (!preg_match('/^\\d+$/', $form_state->getValue('nodejs_uid'))) {
         $form_state->setErrorByName('nodejs_uid', t('Invalid uid - please enter a numeric uid.'));
     }
     if (!preg_match('/^([a-z0-9_]+)$/i', $form_state->getValue('nodejs_channel'))) {
         $form_state->setErrorByName('nodejs_channel', t('Invalid channel name - only numbers, letters and underscores are allowed.'));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (strlen($form_state->getValue('nc_username')) < 3) {
         $form_state->setErrorByName('nc_username', $this->t('The Username is too short you should select a longer one'));
     }
     if (strlen($form_state->getValue('nc_api_key')) < 3) {
         $form_state->setErrorByName('nc_api_key', $this->t('The API Key is too short you should select a longer one'));
     }
 }
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if ($form_state->getValue('intranet_petitions_expired_days') <= 0) {
         $form_state->setErrorByName('intranet_petitions_expired_days', $this->t('Number of days should be > 0.'));
     }
     if ($form_state->getValue('intranet_petitions_likes_level') <= 0) {
         $form_state->setErrorByName('intranet_petitions_likes_level', $this->t('Number of likes level should be > 0.'));
     }
 }
Example #12
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     require_once drupal_get_path('module', 'uc_icepay') . '/api/ParameterValidation.php';
     if (!\Icepay_ParameterValidation::merchantID($form_state->getValue('uc_icepay_merchant_id'))) {
         $form_state->setErrorByName('uc_icepay_merchant_id', t('You have specified an invalid Icepay Merchant ID.'));
     }
     if (!\Icepay_ParameterValidation::secretCode($form_state->getValue('uc_icepay_secret_code'))) {
         $form_state->setErrorByName('uc_icepay_secret_code', t('You have specified an invalid Icepay Secret Code.'));
     }
 }
Example #13
0
 /**
  * Validates the language editing element.
  */
 public function validateCommon(array $form, FormStateInterface $form_state)
 {
     // Ensure sane field values for langcode and name.
     if (!isset($form['langcode_view']) && !preg_match('@^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$@', $form_state->getValue('langcode'))) {
         $form_state->setErrorByName('langcode', $this->t('%field must be a valid language tag as <a href=":url">defined by the W3C</a>.', array('%field' => $form['langcode']['#title'], ':url' => 'http://www.w3.org/International/articles/language-tags/')));
     }
     if ($form_state->getValue('label') != Html::escape($form_state->getValue('label'))) {
         $form_state->setErrorByName('label', $this->t('%field cannot contain any markup.', array('%field' => $form['label']['#title'])));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $id = strtolower(trim($form_state->getValue('id')));
     if (strpos($id, ' ') !== FALSE || $id == 'all') {
         $form_state->setErrorByName('id', $this->t('You have entered an invalid status ID.'));
     }
     if (OrderStatus::load($id)) {
         $form_state->setErrorByName('id', $this->t('This ID is already in use.  Please specify a unique ID.'));
     }
 }
 /**
  * Validates the language editing element.
  */
 public function validateCommon(array $form, FormStateInterface $form_state)
 {
     // Ensure sane field values for langcode and name.
     if (!isset($form['langcode_view']) && preg_match('@[^a-zA-Z_-]@', $form_state->getValue('langcode'))) {
         $form_state->setErrorByName('langcode', $this->t('%field may only contain characters a-z, underscores, or hyphens.', array('%field' => $form['langcode']['#title'])));
     }
     if ($form_state->getValue('label') != String::checkPlain($form_state->getValue('label'))) {
         $form_state->setErrorByName('label', $this->t('%field cannot contain any markup.', array('%field' => $form['label']['#title'])));
     }
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $ip = trim($form_state->getValue('ip'));
     if ($this->ipManager->isBanned($ip)) {
         $form_state->setErrorByName('ip', $this->t('This IP address is already banned.'));
     } elseif ($ip == $this->getRequest()->getClientIP()) {
         $form_state->setErrorByName('ip', $this->t('You may not ban your own IP address.'));
     } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) {
         $form_state->setErrorByName('ip', $this->t('Enter a valid IP address.'));
     }
 }
 /**
  * Implements \Drupal\Core\Form\FormInterface::validateForm().
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $languages = language_list();
     // Count repeated values for uniqueness check.
     $count = array_count_values($form_state->getValue('prefix'));
     foreach ($languages as $langcode => $language) {
         $value = $form_state->getValue(array('prefix', $langcode));
         if ($value === '') {
             if (!$language->isDefault() && $form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_PATH_PREFIX) {
                 // Throw a form error if the prefix is blank for a non-default language,
                 // although it is required for selected negotiation type.
                 $form_state->setErrorByName("prefix][{$langcode}", $this->t('The prefix may only be left blank for the default language.'));
             }
         } elseif (strpos($value, '/') !== FALSE) {
             // Throw a form error if the string contains a slash,
             // which would not work.
             $form_state->setErrorByName("prefix][{$langcode}", $this->t('The prefix may not contain a slash.'));
         } elseif (isset($count[$value]) && $count[$value] > 1) {
             // Throw a form error if there are two languages with the same
             // domain/prefix.
             $form_state->setErrorByName("prefix][{$langcode}", $this->t('The prefix for %language, %value, is not unique.', array('%language' => $language->name, '%value' => $value)));
         }
     }
     // Count repeated values for uniqueness check.
     $count = array_count_values($form_state->getValue('domain'));
     foreach ($languages as $langcode => $language) {
         $value = $form_state->getValue(array('domain', $langcode));
         if ($value === '') {
             if ($form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_DOMAIN) {
                 // Throw a form error if the domain is blank for a non-default language,
                 // although it is required for selected negotiation type.
                 $form_state->setErrorByName("domain][{$langcode}", $this->t('The domain may not be left blank for %language.', array('%language' => $language->name)));
             }
         } elseif (isset($count[$value]) && $count[$value] > 1) {
             // Throw a form error if there are two languages with the same
             // domain/domain.
             $form_state->setErrorByName("domain][{$langcode}", $this->t('The domain for %language, %value, is not unique.', array('%language' => $language->name, '%value' => $value)));
         }
     }
     // Domain names should not contain protocol and/or ports.
     foreach ($languages as $langcode => $name) {
         $value = $form_state->getValue(array('domain', $langcode));
         if (!empty($value)) {
             // Ensure we have exactly one protocol when checking the hostname.
             $host = 'http://' . str_replace(array('http://', 'https://'), '', $value);
             if (parse_url($host, PHP_URL_HOST) != $value) {
                 $form_state->setErrorByName("domain][{$langcode}", $this->t('The domain for %language may only contain the domain name, not a protocol and/or port.', array('%language' => $name)));
             }
         }
     }
     parent::validateForm($form, $form_state);
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $max_links = $form_state->getValue('max_links');
     if ($max_links != '') {
         if (!is_numeric($max_links) || $max_links < 1 || $max_links != round($max_links)) {
             $form_state->setErrorByName('max_links', $this->t("The value of the <em>Maximum links in a sitemap</em> field must be empty, or a positive integer greater than 0."));
         }
     }
     $batch_process_limit = $form_state->getValue('batch_process_limit');
     if (!is_numeric($batch_process_limit) || $batch_process_limit < 1 || $batch_process_limit != round($batch_process_limit)) {
         $form_state->setErrorByName('batch_process_limit', $this->t("The value of the <em>Refresh batch every n links</em> field must be a positive integer greater than 0."));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     // Accept maximum two class value for the selector field.
     $limit = $form_state->getValue('autofloat_span');
     if (substr_count($limit, ',') > 1) {
         $form_state->setErrorByName('autofloat_span', $this->t('Not more than two values.'));
     }
     // Accept maximum two class value for the rejector field.
     $limit = $form_state->getValue('autofloat_div');
     if (substr_count($limit, ',') > 1) {
         $form_state->setErrorByName('autofloat_div', $this->t('Not more than two values.'));
     }
     parent::validateForm($form, $form_state);
 }
Example #20
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $user_id = $form_state->getValue('masquerade_as');
     if (empty($user_id)) {
         $form_state->setErrorByName('masquerade_as', $this->t('The user does not exist. Please enter a valid username.'));
         return;
     }
     $target_account = $this->entityManager->getStorage('user')->load($user_id);
     if ($error = masquerade_switch_user_validate($target_account)) {
         $form_state->setErrorByName('masquerade_as', $error);
     } else {
         $form_state->setValue('masquerade_target_account', $target_account);
     }
 }
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $collection_name = Html::escape($form['searchblox_collection']['#value']);
     try {
         $resp = searchblox_check_collection($collection_name);
         // check weather
     } catch (\Exception $e) {
         $resp = $e->getMessage();
         $form_state->setErrorByName('error', $this->t($resp));
     }
     if ($resp !== true) {
         $form_state->setErrorByName('error', $this->t($resp));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function process(OrderInterface $order, array $form, FormStateInterface $form_state)
 {
     $user = \Drupal::currentUser();
     $cart_config = \Drupal::config('uc_cart.settings');
     $pane = $form_state->getValue(['panes', 'customer']);
     $order->setEmail($pane['primary_email']);
     if ($user->isAuthenticated()) {
         $order->setUserId($user->id());
     } else {
         // Check if the email address is already taken.
         $mail_taken = (bool) \Drupal::entityQuery('user')->condition('mail', $pane['primary_email'])->range(0, 1)->count()->execute();
         if ($cart_config->get('email_validation') && $pane['primary_email'] !== $pane['primary_email_confirm']) {
             $form_state->setErrorByName('panes][customer][primary_email_confirm', t('The e-mail address did not match.'));
         }
         // Invalidate if an account already exists for this e-mail address, and the user is not logged into that account
         if (!$cart_config->get('mail_existing') && !empty($pane['primary_email']) && $mail_taken) {
             $form_state->setErrorByName('panes][customer][primary_email', t('An account already exists for your e-mail address. You will either need to login with this e-mail address or use a different e-mail address.'));
         }
         // If new users can specify names or passwords then...
         if ($cart_config->get('new_account_name') || $cart_config->get('new_account_password')) {
             // Skip if an account already exists for this e-mail address.
             if ($cart_config->get('mail_existing') && $mail_taken) {
                 drupal_set_message(t('An account already exists for your e-mail address. The new account details you entered will be disregarded.'));
             } else {
                 // Validate the username.
                 if ($cart_config->get('new_account_name') && !empty($pane['new_account']['name'])) {
                     $message = user_validate_name($pane['new_account']['name']);
                     $name_taken = (bool) \Drupal::entityQuery('user')->condition('name', $pane['new_account']['name'])->range(0, 1)->count()->execute();
                     if (!empty($message)) {
                         $form_state->setErrorByName('panes][customer][new_account][name', $message);
                     } elseif ($name_taken) {
                         $form_state->setErrorByName('panes][customer][new_account][name', t('The username %name is already taken. Please enter a different name or leave the field blank for your username to be your e-mail address.', array('%name' => $pane['new_account']['name'])));
                     } else {
                         $order->data->new_user_name = $pane['new_account']['name'];
                     }
                 }
                 // Validate the password.
                 if ($cart_config->get('new_account_password')) {
                     if (strcmp($pane['new_account']['pass'], $pane['new_account']['pass_confirm'])) {
                         $form_state->setErrorByName('panes][customer][new_account][pass_confirm', t('The passwords you entered did not match. Please try again.'));
                     }
                     if (!empty($pane['new_account']['pass'])) {
                         $order->data->new_user_hash = \Drupal::service('password')->hash(trim($pane['new_account']['pass']));
                     }
                 }
             }
         }
     }
     return TRUE;
 }
 /**
  * {@inheritdoc}
  */
 public function defaultValuesFormValidate(array $element, array &$form, FormStateInterface $form_state)
 {
     if ($form_state->getValue(['default_value_input', 'default_date_type']) == static::DEFAULT_VALUE_CUSTOM) {
         $is_strtotime = @strtotime($form_state->getValue(['default_value_input', 'default_date']));
         if (!$is_strtotime) {
             $form_state->setErrorByName('default_value_input][default_date', $this->t('The relative start date value entered is invalid.'));
         }
     }
     if ($form_state->getValue(['default_value_input', 'default_end_date_type']) == static::DEFAULT_VALUE_CUSTOM) {
         $is_strtotime = @strtotime($form_state->getValue(['default_value_input', 'default_end_date']));
         if (!$is_strtotime) {
             $form_state->setErrorByName('default_value_input][default_end_date', $this->t('The relative end date value entered is invalid.'));
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $nickname = $form_state->getValue('nickname');
     $firstname = $form_state->getValue('firstname');
     $lastnames = $form_state->getValue('lastnames');
     if (!preg_match('/\\p{L}+/', $nickname) && !empty($nickname)) {
         $form_state->setErrorByName('nickname', $this->t('Please type in a correct nickname'));
     }
     if (!preg_match('/\\p{L}+/', $firstname) && !empty($firstname)) {
         $form_state->setErrorByName('firstname', $this->t('Please type in a correct first name'));
     }
     if (!preg_match('/\\p{L}+/', $lastnames) && !empty($lastnames)) {
         $form_state->setErrorByName('lastnames', $this->t('Please type in correct last names'));
     }
 }
  protected function validatePdfUpload(array &$form, FormStateInterface &$form_state, UploadedFile $file_upload, $file_field_name) {
    /**
     * @var $file_upload \Symfony\Component\HttpFoundation\File\UploadedFile
     */
    if ($file_upload && $file_upload->isValid()) {
      // Move it to somewhere we know.
      $uploaded_filename = $file_upload->getClientOriginalName();

      // Ensure the destination is unique; we deliberately use managed files,
      // but they are keyed on file URI, so we can't save the same one twice.
      $scheme = $this->config('fillpdf.settings')->get('scheme');
      $destination = file_destination(FillPdf::buildFileUri($scheme, 'fillpdf/' . $uploaded_filename), FILE_EXISTS_RENAME);

      // Ensure our directory exists.
      $fillpdf_directory = FillPdf::buildFileUri($scheme, 'fillpdf');
      $directory_exists = file_prepare_directory($fillpdf_directory, FILE_CREATE_DIRECTORY + FILE_MODIFY_PERMISSIONS);

      if ($directory_exists) {
        $file_moved = $this->fileSystem->moveUploadedFile($file_upload->getRealPath(), $destination);

        if ($file_moved) {
          // Create a File object from the uploaded file.
          $new_file = File::create([
            'uri' => $destination,
            'uid' => $this->currentUser()->id(),
          ]);

          $errors = file_validate_extensions($new_file, 'pdf');

          if (count($errors)) {
            $form_state->setErrorByName('upload_pdf', $this->t('Only PDF files are supported, and they must end in .pdf.'));
          }
          else {
            $form_state->setValue('upload_pdf', $new_file);
          }
        }
        else {
          $form_state->setErrorByName('upload_pdf', $this->t("Could not move your uploaded file from PHP's temporary location to Drupal file storage."));
        }
      }
      else {
        $form_state->setErrorByName('upload_pdf', $this->t('Could not automatically create the <em>fillpdf</em> subdirectory. Please create this manually before uploading your PDF form.'));
      }
    }
    else {
      $form_state->setErrorByName('upload_pdf', $this->t('Your PDF could not be uploaded. Did you select one?'));
    }
  }
Example #26
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $edit = $form_state->getValues();
     // Determine if any downloads were modified.
     if (isset($edit['file_download'])) {
         foreach ((array) $edit['file_download'] as $key => $download_modification) {
             // We don't care... it's about to be deleted.
             if ($download_modification['remove']) {
                 continue;
             }
             if ($download_modification['download_limit'] < 0) {
                 $form_state->setErrorByName('file_download][' . $key . '][download_limit', $this->t('A negative download limit does not make sense. Please enter a positive integer, or leave empty for no limit.'));
             }
             if ($download_modification['address_limit'] < 0) {
                 $form_state->setErrorByName('file_download][' . $key . '][address_limit', $this->t('A negative address limit does not make sense. Please enter a positive integer, or leave empty for no limit.'));
             }
             // Some expirations don't need any validation...
             if ($download_modification['time_granularity'] == 'never' || !$download_modification['time_quantity']) {
                 continue;
             }
             // Either use the current expiration, or if there's none,
             // start from right now.
             $new_expiration = _uc_file_expiration_date($download_modification, $download_modification['expiration']);
             if ($new_expiration <= REQUEST_TIME) {
                 $form_state->setErrorByName('file_download][' . $key . '][time_quantity', $this->t('The date %date has already occurred.', ['%date' => \Drupal::service('date.formatter')->format($new_expiration, 'short')]));
             }
             if ($download_modification['time_quantity'] < 0) {
                 $form_state->setErrorByName('file_download][' . $key . '][time_quantity', $this->t('A negative expiration quantity does not make sense. Use the polarity control to determine if the time should be added or subtracted.'));
             }
         }
     }
 }
Example #27
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $uploaded_file = $this->getRequest()->files->get('files[project_upload]', NULL, TRUE);
     if (!($form_state->getValue('project_url') xor !empty($uploaded_file))) {
         $form_state->setErrorByName('project_url', $this->t('You must either provide a URL or upload an archive file to install.'));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     // Confirm that age is numeric.
     if (!intval($form_state->getValue('age'))) {
         $form_state->setErrorByName('age', $this->t('Age needs to be a number'));
     }
 }
Example #29
0
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     // Form submitted, but no modules selected.
     if (!array_filter($form_state->getValue('reinstall'))) {
         $form_state->setErrorByName('reinstall', $this->t('No modules selected.'));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     // Replace all contiguous whitespaces (including tabs and newlines) with a
     // single plain space.
     $form_state->setValue(['date_format'], trim(preg_replace('/\\s+/', ' ', $form_state->getValue(['date_format']))));
     // Validate the letters used in the scheduler date format. All punctuation
     // is accepted, so remove everything except word characters then check that
     // there is nothing else which is not in the list of acceptable date/time
     // letters.
     $no_punctuation = preg_replace('/[^\\w+]/', '', $form_state->getValue(['date_format']));
     if (preg_match_all('/[^' . SCHEDULER_DATE_LETTERS . SCHEDULER_TIME_LETTERS . ']/', $no_punctuation, $extra)) {
         $form_state->setErrorByName('date_format', $this->t('You may only use the letters $date_letters for the date and $time_letters for the time. Remove the extra characters $extra', ['$date_letters' => SCHEDULER_DATE_LETTERS, '$time_letters' => SCHEDULER_TIME_LETTERS, '$extra' => implode(' ', $extra[0])]));
     }
     // If date-only is enabled then check if a valid default time was entered.
     // Leading zeros and seconds can be omitted, eg. 6:30 is considered valid.
     if ($form_state->getValue(['allow_date_only'])) {
         $default_time = date_parse($form_state->getValue(['default_time']));
         if ($default_time['error_count']) {
             $form_state->setErrorByName('default_time', $this->t('The default time should be in the format HH:MM:SS'));
         } else {
             // Insert any possibly omitted leading zeroes.
             $unix_time = mktime($default_time['hour'], $default_time['minute'], $default_time['second']);
             $form_state->setValue(['default_time'], $this->dateFormatter->format($unix_time, 'custom', 'H:i:s'));
         }
     }
     // Check that either the date format has a time part or the date-only option
     // is turned on.
     $time_format = $this->getTimeOnlyFormat($form_state->getValue(['date_format']));
     if ($time_format == '' && !$form_state->getValue(['allow_date_only'])) {
         $form_state->setErrorByName('date_format', $this->t('You must either include a time within the date format or enable the date-only option.'));
     }
 }