Beispiel #1
1
 /**
  * {@inheritdoc}
  */
 public function validate(array &$form, FormStateInterface $form_state)
 {
     $uploaded_files = $form_state->getValue(['upload'], []);
     $trigger = $form_state->getTriggeringElement();
     // Only validate if we are uploading a file.
     if (empty($uploaded_files) && $trigger['#value'] == 'Upload') {
         $form_state->setError($form['widget']['upload'], t('At least one file should be uploaded.'));
     }
 }
 /**
  * Validate the color text field.
  */
 public function validate($element, FormStateInterface $form_state)
 {
     $value = $element['#value'];
     if (strlen($value) == 0) {
         $form_state->setValueForElement($element, '');
         return;
     }
     if (!preg_match('/^#([a-f0-9]{6})$/iD', strtolower($value))) {
         $form_state->setError($element, t("Color must be a 6-digit hexadecimal value, suitable for CSS."));
     }
 }
Beispiel #3
0
 /**
  * Form element validation handler for #type 'number'.
  *
  * Note that #required is validated by _form_validate() already.
  */
 public static function validateNumber(&$element, FormStateInterface $form_state, &$complete_form)
 {
     $value = $element['#value'];
     if ($value === '') {
         return;
     }
     $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
     // Ensure the input is numeric.
     if (!is_numeric($value)) {
         $form_state->setError($element, t('%name must be a number.', array('%name' => $name)));
         return;
     }
     // Ensure that the input is greater than the #min property, if set.
     if (isset($element['#min']) && $value < $element['#min']) {
         $form_state->setError($element, t('%name must be higher than or equal to %min.', array('%name' => $name, '%min' => $element['#min'])));
     }
     // Ensure that the input is less than the #max property, if set.
     if (isset($element['#max']) && $value > $element['#max']) {
         $form_state->setError($element, t('%name must be lower than or equal to %max.', array('%name' => $name, '%max' => $element['#max'])));
     }
     if (isset($element['#step']) && strtolower($element['#step']) != 'any') {
         // Check that the input is an allowed multiple of #step (offset by #min if
         // #min is set).
         $offset = isset($element['#min']) ? $element['#min'] : 0.0;
         if (!NumberUtility::validStep($value, $element['#step'], $offset)) {
             $form_state->setError($element, t('%name is not a valid number.', array('%name' => $name)));
         }
     }
 }
Beispiel #4
0
 /**
  * Form element validation handler for matched_path elements.
  *
  * Note that #maxlength is validated by _form_validate() already.
  *
  * This checks that the submitted value matches an active route.
  */
 public static function validateMatchedPath(&$element, FormStateInterface $form_state, &$complete_form)
 {
     if (!empty($element['#value']) && ($element['#validate_path'] || $element['#convert_path'] != self::CONVERT_NONE)) {
         /** @var \Drupal\Core\Url $url */
         if ($url = \Drupal::service('path.validator')->getUrlIfValid($element['#value'])) {
             if ($url->isExternal()) {
                 $form_state->setError($element, t('You cannot use an external URL, please enter a relative path.'));
                 return;
             }
             if ($element['#convert_path'] == self::CONVERT_NONE) {
                 // Url is valid, no conversion required.
                 return;
             }
             // We do the value conversion here whilst the Url object is in scope
             // after validation has occurred.
             if ($element['#convert_path'] == self::CONVERT_ROUTE) {
                 $form_state->setValueForElement($element, array('route_name' => $url->getRouteName(), 'route_parameters' => $url->getRouteParameters()));
                 return;
             } elseif ($element['#convert_path'] == self::CONVERT_URL) {
                 $form_state->setValueForElement($element, $url);
                 return;
             }
         }
         $form_state->setError($element, t('This path does not exist or you do not have permission to link to %path.', array('%path' => $element['#value'])));
     }
 }
 /**
  * Validates a Geofield generic component based form element.
  *
  * @param array $element
  *   The element being processed.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  * @param array $complete_form
  *   The complete form structure.
  */
 function elementValidate(&$element, FormStateInterface $form_state, &$complete_form)
 {
     $allFilled = TRUE;
     $anyFilled = FALSE;
     $error_label = isset($element['#error_label']) ? $element['#error_label'] : $element['#title'];
     foreach (static::$components as $key => $component) {
         if (!empty($element[$key]['#value'])) {
             if (!is_numeric($element[$key]['#value'])) {
                 $form_state->setError($element[$key], t('@title: @component_title is not numeric.', array('@title' => $error_label, '@component_title' => $component['title'])));
             } elseif (abs($element[$key]['#value']) > $component['range']) {
                 $form_state->setError($element[$key], t('@title: @component_title is out of bounds.', array('@title' => $error_label, '@component_title' => $component['title'])));
             }
         }
         if ($element[$key]['#value'] == '') {
             $allFilled = FALSE;
         } else {
             $anyFilled = TRUE;
         }
     }
     if ($anyFilled && !$allFilled) {
         foreach (self::$components as $key => $component) {
             if ($element[$key]['#value'] == '') {
                 $form_state->setError($element[$key], t('@title: @component_title must be filled too.', array('@title' => $error_label, '@component_title' => $component['title'])));
             }
         }
     }
 }
Beispiel #6
0
 /**
  * Form element validation handler for #type 'uc_quantity'.
  *
  * Note that #required is validated by _form_validate() already.
  */
 public static function validateQuantity(&$element, FormStateInterface $form_state, &$complete_form)
 {
     if (!preg_match('/^\\d+$/', $element['#value'])) {
         $form_state->setError($element, t('The quantity must be a number.'));
     } elseif (empty($element['#allow_zero']) && !$element['#value']) {
         $form_state->setError($element, t('The quantity cannot be zero.'));
     }
 }
Beispiel #7
0
 /**
  * {@inheritDoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     if (!filter_var($form_state->getValue('email_address'), FILTER_VALIDATE_EMAIL)) {
         $form_state->setError($form['email_address'], 'Email address is invalid.');
     }
     if (!$this->validEmailAddress($form_state->getValue('email_address'))) {
         $form_state->setError($form['email_address'], 'Sorry, we only accept Gmail or Yahoo email addresses at this time.');
     }
 }
Beispiel #8
0
 /**
  * Validates the numeric code.
  */
 public function validateNumericCode(array $element, FormStateInterface &$form_state, array $form)
 {
     $currency = $this->getEntity();
     $numeric_code = $element['#value'];
     if ($numeric_code && !preg_match('/^\\d{3}$/i', $numeric_code)) {
         $form_state->setError($element, $this->t('The numeric code must consist of three digits.'));
     } elseif ($currency->isNew()) {
         $loaded_currencies = $this->storage->loadByProperties(['numericCode' => $numeric_code]);
         if ($loaded_currencies) {
             $form_state->setError($element, $this->t('The numeric code is already in use.'));
         }
     }
 }
Beispiel #9
0
 /**
  * #element_validate handler for the "styles" element in settingsForm().
  */
 public function validateStylesValue(array $element, FormStateInterface $form_state)
 {
     $styles_setting = $this->generateStylesSetSetting($element['#value']);
     if ($styles_setting === FALSE) {
         $form_state->setError($element, t('The provided list of styles is syntactically incorrect.'));
     } else {
         $style_names = array_map(function ($style) {
             return $style['name'];
         }, $styles_setting);
         if (count($style_names) !== count(array_unique($style_names))) {
             $form_state->setError($element, t('Each style must have a unique label.'));
         }
     }
 }
Beispiel #10
0
 /**
  * Form element validation handler for URL alias form element.
  *
  * @param array $element
  *   The form element.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The form state.
  */
 public static function validateFormElement(array &$element, FormStateInterface $form_state)
 {
     // Trim the submitted value of whitespace and slashes.
     $alias = rtrim(trim($element['alias']['#value']), " \\/");
     if (!empty($alias)) {
         $form_state->setValueForElement($element['alias'], $alias);
         // Validate that the submitted alias does not exist yet.
         $is_exists = \Drupal::service('path.alias_storage')->aliasExists($alias, $element['langcode']['#value'], $element['source']['#value']);
         if ($is_exists) {
             $form_state->setError($element, t('The alias is already in use.'));
         }
     }
     if ($alias && $alias[0] !== '/') {
         $form_state->setError($element, t('The alias needs to start with a slash.'));
     }
 }
 public function validateOptionsForm(&$form, FormStateInterface $form_state)
 {
     // Require a key if the format is key.
     if ($form_state->getValue(array('options', 'format')) == 'key' && $form_state->getValue(array('options', 'key')) == '') {
         $form_state->setError($form['key'], $this->t('You have to enter a key if you want to display a key of the data.'));
     }
 }
Beispiel #12
0
  /**
   * {@inheritdoc}
   */
  protected function validateEntityStrings(array &$form, array $values, FormStateInterface $form_state) {
    $uids = array();
    $missing = array();
    foreach ($values as $value) {
      if (Unicode::strtolower($value) === Unicode::strtolower(\Drupal::config('user.settings')->get('anonymous'))) {
        $uids[] = 0;
      }
      else {
        $missing[strtolower($value)] = $value;
      }
    }

    if (!$missing) {
      return $uids;
    }

    $result = Database::getConnection()->query("SELECT * FROM {users} WHERE name IN (:names)", array(':names' => array_values($missing)));
    foreach ($result as $account) {
      unset($missing[strtolower($account->name)]);
      $uids[] = $account->uid;
    }

    if ($missing) {
      $form_state->setError($form, $this->formatPlural(count($missing), 'Unable to find user: @users', 'Unable to find users: @users', array('@users' => implode(', ', $missing))));
    }

    return $uids;
  }
Beispiel #13
0
 /**
  * {@inheritdoc}
  */
 public static function value(array &$element, &$input, FormStateInterface $form_state)
 {
     if (isset($input['filefield_imce']['file_path']) && $input['filefield_imce']['file_path'] != '') {
         $instance = entity_load('field_config', $element['#entity_type'] . '.' . $element['#bundle'] . '.' . $element['#field_name']);
         $field_settings = $instance->getSettings();
         $scheme = $field_settings['uri_scheme'];
         $wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
         $file_directory_prefix = $scheme == 'private' ? 'system/files' : $wrapper->getDirectoryPath();
         $uri = preg_replace('/^' . preg_quote(base_path() . $file_directory_prefix . '/', '/') . '/', $scheme . '://', $input['filefield_imce']['file_path']);
         // Resolve the file path to an FID.
         $fid = db_select('file_managed', 'f')->condition('uri', rawurldecode($uri))->fields('f', array('fid'))->execute()->fetchField();
         if ($fid) {
             $file = file_load($fid);
             if (filefield_sources_element_validate($element, $file)) {
                 if (!in_array($file->id(), $input['fids'])) {
                     $input['fids'][] = $file->id();
                 }
             }
         } else {
             $form_state->setError($element, t('The selected file could not be used because the file does not exist in the database.'));
         }
         // No matter what happens, clear the value from the file path field.
         $input['filefield_imce']['file_path'] = '';
     }
 }
 /**
  * Form validation handler for widget elements.
  *
  * @param array $element
  *   The form element.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The form state.
  */
 public static function validateElement(array $element, FormStateInterface $form_state)
 {
     if ($element['#required'] && $element['#value'] == '_none') {
         $form_state->setError($element, t('@name field is required.', array('@name' => $element['#title'])));
     }
     // Massage submitted form values.
     // Drupal\Core\Field\WidgetBase::submit() expects values as
     // an array of values keyed by delta first, then by column, while our
     // widgets return the opposite.
     if (is_array($element['#value'])) {
         $values = array_values($element['#value']);
     } else {
         $values = array($element['#value']);
     }
     // Filter out the 'none' option. Use a strict comparison, because
     // 0 == 'any string'.
     $index = array_search('_none', $values, TRUE);
     if ($index !== FALSE) {
         unset($values[$index]);
     }
     // Transpose selections from field => delta to delta => field.
     $items = array();
     foreach ($values as $value) {
         $items[] = array($element['#key_column'] => $value);
     }
     $form_state->setValueForElement($element, $items);
 }
 /**
  * {@inheritdoc}
  */
 public function elementValidateRequired($element, FormStateInterface $form_state)
 {
     // Set a custom validation error on the #required element.
     if (!empty($element['#required_but_empty']) && isset($element['#form_test_required_error'])) {
         $form_state->setError($element, $element['#form_test_required_error']);
     }
 }
 /**
  * @covers ::setError
  */
 public function testSetError()
 {
     $element = ['#foo' => 'bar'];
     $message = 'bar';
     $this->decoratedFormState->setError($element, $message)->shouldBeCalled();
     $this->assertSame($this->formStateDecoratorBase, $this->formStateDecoratorBase->setError($element, $message));
 }
 /**
  * {@inheritdoc}
  */
 public static function value(array &$element, &$input, FormStateInterface $form_state)
 {
     if (isset($input['filefield_reference']['autocomplete']) && strlen($input['filefield_reference']['autocomplete']) > 0 && $input['filefield_reference']['autocomplete'] != FILEFIELD_SOURCE_REFERENCE_HINT_TEXT) {
         $matches = array();
         if (preg_match('/\\[fid:(\\d+)\\]/', $input['filefield_reference']['autocomplete'], $matches)) {
             $fid = $matches[1];
             if ($file = file_load($fid)) {
                 // Remove file size restrictions, since the file already exists on
                 // disk.
                 if (isset($element['#upload_validators']['file_validate_size'])) {
                     unset($element['#upload_validators']['file_validate_size']);
                 }
                 // Check that the user has access to this file through
                 // hook_download().
                 if (!$file->access('download')) {
                     $form_state->setError($element, t('You do not have permission to use the selected file.'));
                 } elseif (filefield_sources_element_validate($element, (object) $file, $form_state)) {
                     if (!in_array($file->id(), $input['fids'])) {
                         $input['fids'][] = $file->id();
                     }
                 }
             } else {
                 $form_state->setError($element, t('The referenced file could not be used because the file does not exist in the database.'));
             }
         }
         // No matter what happens, clear the value from the autocomplete.
         $input['filefield_reference']['autocomplete'] = '';
     }
 }
Beispiel #18
0
 /**
  * Validates the tag field.
  */
 public function validateTag(array $element, FormStateInterface $form_state, array $form)
 {
     $tag = $element['#value'];
     if (!empty($tag) && !preg_match('/[a-zA-Z0-9]+/', $tag)) {
         $form_state->setError($element, $this->t('The tag must be a single word.'));
     }
 }
Beispiel #19
0
 /**
  * Flags an element as having an error.
  *
  * @param string $message
  *   (optional) The error message to present to the user.
  *
  * @return $this
  *
  * @throws \BadMethodCallException
  *   When the element instance was not constructed with a valid form state
  *   object.
  */
 public function setError($message = '')
 {
     if (!$this->formState) {
         throw new \BadMethodCallException('The element instance must be constructed with a valid form state object to use this method.');
     }
     $this->formState->setError($this->array, $message);
     return $this;
 }
Beispiel #20
0
 /**
  * {@inheritdoc}
  */
 public static function validateValue(array &$element, FormStateInterface $form_state, array $form)
 {
     if (!empty($element['#value'])) {
         if (!UrlHelper::isValid($element['#value'], TRUE)) {
             $form_state->setError($element, t('The entered Tumblr URI is not valid.'));
         }
     }
 }
Beispiel #21
0
 /**
  * Form element validation handler for #type 'url'.
  *
  * Note that #maxlength and #required is validated by _form_validate() already.
  */
 public static function validateUrl(&$element, FormStateInterface $form_state, &$complete_form)
 {
     $value = trim($element['#value']);
     $form_state->setValueForElement($element, $value);
     if ($value !== '' && !UrlHelper::isValid($value, TRUE)) {
         $form_state->setError($element, t('The URL %url is not valid.', array('%url' => $value)));
     }
 }
 /**
  * Form element validation handler for #type 'email'.
  *
  * Note that #maxlength and #required is validated by _form_validate() already.
  */
 public static function validateEmail(&$element, FormStateInterface $form_state, &$complete_form)
 {
     $value = trim($element['#value']);
     $form_state->setValueForElement($element, $value);
     if ($value !== '' && !valid_email_address($value)) {
         $form_state->setError($element, t('The email address %mail is not valid.', array('%mail' => $value)));
     }
 }
 /**
  * Verify that element is a valid username.
  */
 public static function validUser($element, FormStateInterface $form_state)
 {
     if ($element['#value'] !== '') {
         $count = \Drupal::database()->select('users_field_data', 'u')->condition('name', $element['#value'])->countQuery()->execute()->fetchField();
         if (intval($count) != 1) {
             $form_state->setError($element, t('The @field field should be a valid username.', array('@field' => $element['#title'])));
         }
     }
 }
Beispiel #24
0
 public function validateOptionsForm(&$form, FormStateInterface $form_state)
 {
     $role = $form_state->getValue(array('access_options', 'role'));
     $role = array_filter($role);
     if (!$role) {
         $form_state->setError($form['role'], $this->t('You must select at least one role if type is "by role"'));
     }
     $form_state->setValue(array('access_options', 'role'), $role);
 }
Beispiel #25
0
 /**
  * {@inheritdoc}
  */
 public static function validateValue(array &$element, FormStateInterface $form_state, array $form)
 {
     if (!empty($element['#value'])) {
         $validator = new EmailValidator();
         if (!$validator->isValid($element['#value'], TRUE)) {
             $form_state->setError($element, t('The entered email address is not valid.'));
         }
     }
 }
 /**
  * Validates a password_confirm element.
  */
 public static function validatePasswordConfirm(&$element, FormStateInterface $form_state, &$complete_form)
 {
     $pass1 = trim($element['pass1']['#value']);
     $pass2 = trim($element['pass2']['#value']);
     if (strlen($pass1) > 0 || strlen($pass2) > 0) {
         if (strcmp($pass1, $pass2)) {
             $form_state->setError($element, t('The specified passwords do not match.'));
         }
     } elseif ($element['#required'] && $form_state->getUserInput()) {
         $form_state->setError($element, t('Password field is required.'));
     }
     // Password field must be converted from a two-element array into a single
     // string regardless of validation results.
     $form_state->setValueForElement($element['pass1'], NULL);
     $form_state->setValueForElement($element['pass2'], NULL);
     $form_state->setValueForElement($element, $pass1);
     return $element;
 }
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     $machine_name = $form_state->getValue('machine_name');
     $cached_values = $this->tempstore->get($this->tempstore_id)->get($this->machine_name);
     foreach ($this->getContexts($cached_values) as $id => $context) {
         if ($context['machine_name'] == $machine_name) {
             $form_state->setError($form['machine_name'], $this->t('That machine name is in use by another context definition.'));
         }
     }
 }
Beispiel #28
0
 public function validateOptionsForm(&$form, FormStateInterface $form_state)
 {
     $custom_fields = array('output_lifespan', 'results_lifespan');
     foreach ($custom_fields as $field) {
         $cache_options = $form_state->getValue('cache_options');
         if ($cache_options[$field] == 'custom' && !is_numeric($cache_options[$field . '_custom'])) {
             $form_state->setError($form[$field . '_custom'], $this->t('Custom time values must be numeric.'));
         }
     }
 }
Beispiel #29
0
 /**
  * Validate that the time values convert to something usable.
  */
 public function validateValidTime(&$form, FormStateInterface $form_state, $operator, $value)
 {
     $operators = $this->operators();
     if ($operators[$operator]['values'] == 1) {
         $convert = strtotime($value['value']);
         if (!empty($form['value']) && ($convert == -1 || $convert === FALSE)) {
             $form_state->setError($form['value'], $this->t('Invalid date format.'));
         }
     } elseif ($operators[$operator]['values'] == 2) {
         $min = strtotime($value['min']);
         if ($min == -1 || $min === FALSE) {
             $form_state->setError($form['min'], $this->t('Invalid date format.'));
         }
         $max = strtotime($value['max']);
         if ($max == -1 || $max === FALSE) {
             $form_state->setError($form['max'], $this->t('Invalid date format.'));
         }
     }
 }
 /**
  * Form element validation handler for URL alias form element.
  *
  * @param array $element
  *   The form element.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The form state.
  */
 public static function validateFormElement(array &$element, FormStateInterface $form_state)
 {
     $value = $element['#value'];
     if (empty($value)) {
         return;
     }
     $provider_manager = \Drupal::service('video_embed_field.provider_manager');
     $enabled_providers = $provider_manager->loadDefinitionsFromOptionList($element['#allowed_providers']);
     if (!$provider_manager->filterApplicableDefinitions($enabled_providers, $value)) {
         $form_state->setError($element, static::getProviderErrorMessage());
     }
 }