Form element validation handler for entity_autocomplete elements.
359516
public static function validateEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $duplicated_values = $value = [];

    // Load the current Group so we can see if there are existing members.
    $group = _social_group_get_current_group();

    // Grab all the input values so we can get the ID's out of them.
    $input_values = Tags::explode($element['#value']);
    foreach ($input_values as $input) {
      $match = static::extractEntityIdFromAutocompleteInput($input);
      if ($match === NULL) {
        $options = $element['#selection_settings'] + [
          'target_type' => $element['#target_type'],
          'handler' => $element['#selection_handler'],
        ];

        /* @var /Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler */
        $handler = \Drupal::service('plugin.manager.entity_reference_selection')->getInstance($options);
        $autocreate = (bool) $element['#autocreate'] && $handler instanceof SelectionWithAutocreateInterface;
        // Try to get a match from the input string when the user didn't use
        // the autocomplete but filled in a value manually.
        // Got this from the parent::validateEntityAutocomplete.
        $match = static::matchEntityByTitle($handler, $input, $element, $form_state, !$autocreate);
      }

      if ($match !== NULL) {
        $value[$match] = [
          'target_id' => $match,
        ];

        $account = User::load($match);
        // User is already a member, add it to an array for the Form element
        // to render an error after all checks are gone.
        if ($group->getMember($account)) {
          $duplicated_values[] = $input;
        }

        // Validate input for every single user. This way we make sure that
        // The element validates one, or more users added in the autocomplete.
        // This is because Group doesn't allow adding multiple users at once,
        // so we need to validate single users, if they all pass we can add
        // them all in the _social_group_action_form_submit.
        parent::validateEntityAutocomplete($element, $form_state, $complete_form);
      }
    }

    // If we have duplicates, provide an error message.
    if (!empty($duplicated_values)) {
      $usernames = implode(', ', $duplicated_values);

      $message = \Drupal::translation()->formatPlural(count($duplicated_values),
        "@usernames is already member of the group, you can't add them again",
        "@usernames are already members of the group, you can't add them again",
        ['@usernames' => $usernames]
      );

      // We have to kick in a form set error here, or else the
      // GroupContentCardinalityValidator will kick in and show a faulty
      // error message. Alter this later when Group supports multiple members.
      $form_state->setError($element, $message);
      return;
    }

    if ($value) {
      $form_state->setValue('entity_id_new', $value);
    }
  }
104602
function(form, e, eventData) {

    e.preventDefault();

    var formElement = $(form);

    if(formElement.hasClass('success')) {
      getAvailability();
      hideBookingPage();
      return;
    }

    // Abort if form is submitting, have submitted or does not validate
    if(formElement.hasClass('loading') || formElement.hasClass('error') || !e.target.checkValidity()) {
      var submitButton = formElement.find('.bookingjs-form-button');
      submitButton.addClass('button-shake');
      setTimeout(function() {
        submitButton.removeClass('button-shake');
      }, 500);
      return;
    }

    var formData = {};
    $.each(formElement.serializeArray(), function(i, field) {
      formData[field.name] = field.value;
    });

    formElement.addClass('loading');

    utils.doCallback('submitBookingForm', formData);

    // Call create event endpoint
    timekitCreateBooking(formData, eventData).then(function(response){

      formElement.find('.booked-email').html(formData.email);
      formElement.removeClass('loading').addClass('success');

    }).catch(function(response){

      showBookingFailed(formElement)

    });

  }
1014308
def validate_element(self, value):
        
        # If value is str is it considered valid.  Satisfies "required=True".
        if isinstance(value, bytes):
            try:
                six.text_type(value, 'UTF-8')
            except UnicodeDecodeError as err:
                try:
                    _ = self.name
                except AttributeError:
                    validation_error = ValidationError(
                        'Field encountered non-UTF-8 string %r: %s' % (value,
                                                                       err))
                else:
                    validation_error = ValidationError(
                        'Field %s encountered non-UTF-8 string %r: %s' % (
                            self.name, value, err))
                    validation_error.field_name = self.name
                raise validation_error
        else:
            return super(StringField, self).validate_element(value)
        return value
881942
function(e){
		 //the onBlur from an old version of inputex took in the AutoComplete.js file
	   if (this.hiddenEl.value != this.el.value && this.el.value != this.options.typeInvite) this.el.value = this.hiddenEl.value;
	     if(this.el.value == '' && this.options.typeInvite) {
	          Dom.addClass(this.divEl, "inputEx-typeInvite");
			   if (this.el.value == '') this.el.value = this.options.typeInvite;
      }
  }
565891
def end_element(self, tag):
        """"""
        if tag == u'form':
            self.forms.append(self.form)
            self.form = None
650035
function validateAndGetQuerySelector (selector) {
  try {
    var el = document.querySelector(selector);
    if (!el) {
      warn('No element was found matching the selector: "%s"', selector);
    }
    return el;
  } catch (e) {  // Capture exception if it's not a valid selector.
    warn('"%s" is not a valid selector', selector);
    return undefined;
  }
}
579785
def _get_aria_autocomplete(self, field):
        

        tag_name = field.get_tag_name()
        input_type = None
        if field.has_attribute('type'):
            input_type = field.get_attribute('type').lower()
        if (
            (tag_name == 'TEXTAREA')
            or (
                (tag_name == 'INPUT')
                and (not (
                    (input_type == 'button')
                    or (input_type == 'submit')
                    or (input_type == 'reset')
                    or (input_type == 'image')
                    or (input_type == 'file')
                    or (input_type == 'checkbox')
                    or (input_type == 'radio')
                    or (input_type == 'hidden')
                ))
            )
        ):
            value = None
            if field.has_attribute('autocomplete'):
                value = field.get_attribute('autocomplete').lower()
            else:
                form = self.parser.find(field).find_ancestors(
                    'form'
                ).first_result()
                if (form is None) and (field.has_attribute('form')):
                    form = self.parser.find(
                        '#' + field.get_attribute('form')
                    ).first_result()
                if (form is not None) and (form.has_attribute('autocomplete')):
                    value = form.get_attribute('autocomplete').lower()
            if value == 'on':
                return 'both'
            elif (
                (field.has_attribute('list'))
                and (self.parser.find(
                    'datalist[id="' + field.get_attribute('list') + '"]'
                ).first_result() is not None)
            ):
                return 'list'
            elif value == 'off':
                return 'none'
        return None
779696
function elementMatches (el, selector) {
  if (el.matches) { return el.matches(selector) }
  if (el.msMatchesSelector) { return el.msMatchesSelector(selector) }
  if (el.webkitMatchesSelector) { return el.webkitMatchesSelector(selector) }
}
971972
def validate_extra_context(ctx, param, value):
    """"""
    for s in value:
        if '=' not in s:
            raise click.BadParameter(
                'EXTRA_CONTEXT should contain items of the form key=value; '
                "'{}' doesn't match that form".format(s)
            )

    # Convert tuple -- e.g.: (u'program_name=foobar', u'startsecs=66')
    # to dict -- e.g.: {'program_name': 'foobar', 'startsecs': '66'}
    return collections.OrderedDict(s.split('=', 1) for s in value) or None
905757
function accept(&$renderer)
    {
        $renderer->startForm($this);
        foreach (array_keys($this->_elements) as $key) {
            $element =& $this->_elements[$key];
            $elementName = $element->getName();
            $required    = ($this->isElementRequired($elementName) && !$element->isFrozen());
            $error       = $this->getElementError($elementName);
            $element->accept($renderer, $required, $error);
        }
        $renderer->finishForm($this);
    }
1007320
public function autocomplete($config = array())
    {
        $config = new ObjectConfigJson($config);
        $config->append(array(
            'element'  => null,
            'options_callback' => null, // wraps the call to select2 options in JavaScript, can be used to add JS code
            'options'  => array(
                'minimumInputLength' => 2,
                'validate'      => false, //Toggle if the forms validation helper is loaded
                'queryVarName'  => 'search',
                'width'         => 'resolve',
                'name'          => '',
                'model'		    => $config->model,
                'placeholder'   => $config->prompt,
                'allowClear'    => $config->deselect,
                'value'         => $config->value,
                'text'          => $config->text,
                'selected'      => $config->selected,
                'url'           => $config->ajax_url,
                'multiple'      => false
            )
        ))->append(array(
            'options' => array(
                'label' => $config->text
            )
        ));

        $html ='';

        if (!$config->options->url instanceof HttpUrl) {
            $config->options->url = $this->getObject('lib:http.url', ['url' => $config->options->url]);
        }

        if(!empty($config->name))
        {
            $config->options->url->setQuery(array('fields['.$config->name.']' => $config->value.','.$config->text), true);
            $config->options->url = (string)$config->options->url;
        }

        $options   = $config->options;
        $signature = md5('autocomplete-'.$config->element.$config->options_callback.$options);

        if($config->element && !static::isLoaded($signature))
        {
            $options = (string) $options;

            if ($config->options_callback) {
                $options = $config->options_callback.'('.$options.')';
            }

            $html .= $this->select2(array('element' => false));

            if (!static::isLoaded('kodekit-select2-autocomplete')) {
                $html .= '<script>
                if(!Kodekit) {
                    var Kodekit = typeof Koowa !== "undefined" ?  Koowa : {};
                }
                
                Kodekit.getSelect2Options = function(options) {
                    var defaults = {
                        width: "resolve",
                        minimumInputLength: 2,
                        theme: "bootstrap",
                        ajax: {
                            url: options.url,
                            delay: 100,
                            data: function (params) {
                                var page  = params.page || 1,  // page is the one-based page number tracked by Select2
                                    query = {
                                        limit: 10, // page size
                                        offset: (page-1)*10
                                    };
                                query[options.queryVarName] = params.term;
            
                                return query;
                            },
                            processResults: function (data, page) {
                                var results = [],
                                    more = (page * 10) < data.meta.total; // whether or not there are more results available
            
                                kQuery.each(data.data, function(i, item) {
                                    // Change format to what select2 expects
                                    item.id   = item.attributes[options.value];
                                    item.text = item.attributes[options.text];
            
                                    results.push(item);
                                });
            
                                // notice we return the value of more so Select2 knows if more results can be loaded
                                return {results: results, more: more};
                            }
                        }
                    };
                    
                    var settings = kQuery.extend( {}, defaults, options);
                    
                    return settings;
                };
                </script>';

                static::setLoaded('kodekit-select2-autocomplete');
            }

            $html .= '<script>
            kQuery(function($){
                $("'.$config->element.'").select2(Kodekit.getSelect2Options('.$options.'));
            });</script>';

            static::setLoaded($signature);
        }

        return $html;
    }
278403
function validateElement(item) {
      if (!item) return
      if (!__passed) {
        __errors.push({
          element: item.element,
          type: item.type
        })
        if (item.callback) item.callback()
      } else {
        convertToObject($(item.element).array[0].getAttribute('name'), $(item.element).array[0].value)
      }
    }
821354
protected function performValidation()
    {
        // All the fixed fields declared above are objects that MUST use keys that match the regular expression: ^[a-zA-Z0-9\.\-_]+$.
        foreach (array_keys($this->attributes()) as $attribute) {
            if (is_array($this->$attribute)) {
                foreach ($this->$attribute as $k => $v) {
                    if (!preg_match('~^[a-zA-Z0-9\.\-_]+$~', $k)) {
                        $this->addError("Invalid key '$k' used in Components Object for attribute '$attribute', does not match ^[a-zA-Z0-9\.\-_]+\$.");
                    }
                }
            }
        }
    }
86757
protected function selectionHandler()
    {
        $userCount = count($this->choices);
        if ($userCount > static::MAX_USER_CHOICES) {
            $this->autocomplete();
        } elseif ($userCount > 1) {
            $this->selector();
        } elseif (1 === $userCount) {
            $this->editor($this->choices[0]);
        }
    }
1187057
protected function registerElements() {
		$this->action_mode = self::ACTION_GET;
		
		$validatorBool = new \OWeb\utils\inputManagement\validators\Boolean();
		
		$jsString = new \OWeb\utils\inputManagement\validators\JsString();
		
		$this->setAction('refresh');
		
		$active = new \Controller\OWeb\Helpers\Form\Elements\Text();
		$active->init();
		$active->setName('active');
		$active->setTitle('Active');
		$active->setDescription("Which panel is currently open.");
		$active->addValidator(new \OWeb\utils\inputManagement\validators\Integer());
		$active->addValidator(new \OWeb\utils\inputManagement\validators\CanBeEmpty());
		$active->setVal(0);
		$this->addDisplayElement($active);
		
		$animate = new \Controller\OWeb\Helpers\Form\Elements\Text();
		$animate->init();
		$animate->setName('animate');
		$animate->setTitle('Animate');
		$animate->setVal('Animate');
		$animate->addValidator($jsString);
		$animate->setDescription("If and how to animate changing panels.");
		//$this->addDisplayElement($animate);
		
		$collapsible = new \Controller\OWeb\Helpers\Form\Elements\Radio();
		$collapsible->init();
		$collapsible->setName('collapsible');
		$collapsible->setTitle('Collapsible');
		$collapsible->add("true", "true");
		$collapsible->add("false", "false");
		$collapsible->addValidator($validatorBool);
		$collapsible->setVal('true');
		$collapsible->setDescription("hether all the sections can be closed at once. Allows collapsing the active section");
		$this->addDisplayElement($collapsible);
		
		$disabled = new \Controller\OWeb\Helpers\Form\Elements\Radio();
		$disabled->init();
		$disabled->setName('disabled');
		$disabled->setTitle('Disabled');
		$disabled->add("true", "true");
		$disabled->add("false", "false");
		$disabled->addValidator($validatorBool);
		$disabled->setVal('false');
		$disabled->setDescription("Disables the accordion if set to true.");
		$this->addDisplayElement($disabled);
		
		$event = new \Controller\OWeb\Helpers\Form\Elements\Text();
		$event->init();
		$event->setName('event');
		$event->setTitle('Event');
		$event->setVal('click');
		$event->addValidator($jsString);
		$event->setDescription("The event that accordion headers will react to in order to activate the associated panel. Multiple events can be specified, separated by a space.");
		$this->addDisplayElement($event);
		
		$heightStyle = new \Controller\OWeb\Helpers\Form\Elements\Select();
		$heightStyle->init();
		$heightStyle->setName('heightStyle');
		$heightStyle->setTitle('Height Style');
		$heightStyle->add("Auto", "auto");
		$heightStyle->add("Fill", "fill");
		$heightStyle->add("Content", "content");
		$heightStyle->addValidator($jsString);
		$heightStyle->setVal('auto');
		$heightStyle->setDescription("Controls the height of the accordion and each panel.");
		$this->addDisplayElement($heightStyle);
		
		$submit = new \Controller\OWeb\Helpers\Form\Elements\Submit();
		$submit->init();
		$submit->setVal("Refresh");
		$this->addDisplayElement($submit);
	}
757030
public static function processAutocomplete(&$element, FormStateInterface $form_state, &$complete_form) {
    $element = parent::processAutocomplete($element, $form_state, $complete_form);
    $element['#attached']['library'][] = 'webform_strawberryfield/webform_strawberryfield.metadataauth.autocomplete';
    $element['#attached']['drupalSettings'] = [
        'webform_strawberryfield_autocomplete' => [],
      ];

    $element['#attributes']['data-strawberry-autocomplete'] = 'wikidata';
    return $element;
  }
1170982
public static function validatePasswordUpdate(&$element, FormStateInterface $form_state, &$complete_form) {
    $pass1 = trim($element['pass1']['#value']);
    $pass2 = trim($element['pass2']['#value']);
    $oldpass = trim($element['oldpass']['#value']);
    if (strlen($pass1) > 0 || strlen($pass2) > 0) {
      if (strcmp($pass1, $pass2)) {
        $form_state->setError($element, t('The specified passwords do not match.'));
      }
      elseif (empty($oldpass)) {
        $form_state->setError($element, t('Old password is required.'));
      }
    }
    elseif ($element['#required'] && $form_state->getUserInput()) {
      $form_state->setError($element, t('Password field is required.'));
    }

    $form_state->setValueForElement($element['pass1'], NULL);
    $form_state->setValueForElement($element['pass2'], NULL);
    $form_state->setValueForElement($element, ['password' => $pass1, 'password_old' => $oldpass]);

    return $element;
  }