validate submitted form

@param array $values as $form_state['values'] from drupal form api
@param array $storage as $form_state['storage'] from drupal form api

@return array in form array($errors, $warnings)to be thrown by form api
193779
public function drupalFormValidate($values, $storage)  {
    $this->populateFromDrupalForm($values, $storage);
    list($errors, $warnings) = $this->validate($values);

    // since failed mapping rows in form, don't populate ->ldapUserSynchMappings, need to validate these from values
    foreach ($values as $field => $value) {
      $parts = explode('__', $field);
      // since synch mapping fields are in n-tuples, process entire n-tuple at once (on field == configurable_to_drupal)
      if (count($parts) != 4 || $parts[1] !== 'sm' || $parts[2] != 'configurable_to_drupal') {
        continue;
      }
      list($direction, $discard, $column_name, $i) = $parts;
      $action = $storage['synch_mapping_fields'][$direction][$i]['action'];
      $tokens = array();
      $row_mappings = array();
      foreach (array('remove', 'configurable_to_drupal', 'configurable_to_ldap', 'convert', 'direction', 'ldap_attr', 'user_attr', 'user_tokens') as $column_name) {
        $input_name = join('__', array('sm', $column_name, $i));
        $row_mappings[$column_name] = isset($values[$input_name]) ? $values[$input_name] : NULL;
      }

      $has_values = $row_mappings['ldap_attr'] || $row_mappings['user_attr'];
      if ($has_values) {
        $tokens['%ldap_attr'] = $row_mappings['ldap_attr'];
        $row_descriptor = t("server %sid row mapping to ldap attribute %ldap_attr", $tokens);
        $tokens['!row_descriptor'] = $row_descriptor;
        if (!$row_mappings['direction']) {
          $input_name = join('__', array('sm', 'direction', $i));
          $errors[$input_name] = t('No mapping direction given in !row_descriptor', $tokens);
        }
        if ($direction == LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER && $row_mappings['user_attr'] == 'user_tokens') {
          $input_name = join('__', array('sm', 'user_attr', $i));
          $errors[$input_name] =  t('User tokens not allowed when mapping to Drupal user.  Location: !row_descriptor', $tokens);
        }
        if (!$row_mappings['ldap_attr']) {
          $input_name = join('__', array('sm', 'ldap_attr', $i));
          $errors[$input_name] = t('No ldap attribute given in !row_descriptor', $tokens);
        }
        if (!$row_mappings['user_attr']) {
          $input_name = join('__', array('sm', 'user_attr', $i));
          $errors[$input_name] = t('No user attribute given in !row_descriptor', $tokens);
        }
      }

    }
    return array($errors, $warnings);
  }
1018529
protected function validateArray(array $values, $context)
    {
        foreach ($values as $key => $value) {
            $valid = $this->getValidationChain()
                ->validates($value, $context);
            if (!$valid) {
                $this->setInvalid($key);
            }
        }
    }
911881
protected function validate(array $rules, bool $throwError = true)
    {
        $validations = [];
        $data = [];
        foreach ($rules as $key => $rule) {
            $value = $this->request->get($key);
            $violations = $this->validator->validate($value, $rule);
            if (count($violations) > 0) {
                $validations[$key] = [];
                foreach ($violations as $violation) {
                    $validations[$key][] = $violation->getMessage();
                }
            } else {
                $data[$key] = $value;
            }
        }
        if ($throwError && count($validations)) {
            throw new HttpValidationException($validations);
        }
        return $data;
    }
563326
protected function validate(array &$data)
    {
        $messages = [];
        if (isset($data['inserts']) && !empty($data['inserts'])) {
            array_push($messages, ['warning', sprintf('Found %s new files. New, not original files may increase the risk of instability.', count($data['inserts']))]);
        }
        if (isset($data['deletes']) && !empty($data['deletes'])) {
            array_push($messages, ['warning', sprintf('%s files has been deleted. Deleting system files may increase the risk of instability.', count($data['deletes']))]);
        }
        if (isset($data['updates']) && !empty($data['updates'])) {
            array_push($messages, ['warning', sprintf('%s files has been changed. File modifications are unacceptable and can increase the risk of instability.', count($data['updates']))]);
        }
        $data = array_merge($data, ['messages' => $messages]);
        return $data;
    }
64681
public function valid(array $values, $populate = true)
    {
        foreach($this->getElements() as $index => &$element) {
            if(!array_key_exists($index, $values)) {
                if(is_a($element, 'FrenchFrogs\Form\Element\Boolean')){
                    $values[$index] = 0;
                } else {
                    $values[$index] = '';
                }
            }

            $element->valid($values[$index]);

            if (!$element->isValid()) {
                $this->getValidator()->addError($index, $element->getErrorAsString());
            }

        }

        return $this;
    }
986992
public function config_form_validation(array $data, $files = array()) : array {
        $errors = parent::config_form_validation($data, $files);

        if ($data['configdata']['uniquevalues']) {
            $errors['configdata[uniquevalues]'] = get_string('errorconfigunique', 'customfield_checkbox');
        }

        return $errors;
    }
339033
private function isValueValid(array $values): bool
    {
        foreach ($values as $value) {
            if (\preg_match("/[^\t\r\n\x20-\x7e\x80-\xfe]|\r\n/", $value)) {
                return false;
            }
        }

        return true;
    }
425729
public static function validate($request, $rules, $messages=[])
    {
        $errors = [];
        $files = $request->getUploadedFiles();

        foreach ($rules as $field => $rule)
        {
            try
            {
                if ($rule instanceof v)
                {
                    // check if the field is for file
                    if (isset($files[$field]))
                    {
                        if (is_array($files[$field])) // multiple file
                        {
                            $files = $files[$field];
                            foreach ($files as $file_row)
                            {
                                if ($file_row instanceof UploadedFile)
                                {
                                    $rule->setName(str_title(ucfirst($field)))->assert(new \SplFileInfo($file_row->file));
                                }
                            }
                        }
                        else // single file
                        {
                            if ($files[$field] instanceof UploadedFile)
                            {
                                $rule->setName(str_title(ucfirst($field)))->assert(new \SplFileInfo($files[$field]->file));
                            }
                        }
                    }
                    else
                    {
                        $rule->setName(str_title(ucfirst($field)))->assert($request->getParam($field));
                    }
                }
                else
                {
                    \Log::error("Error: Rule must be Respect\Validation\Validator object");
                }
            } catch (NestedValidationException $e) {
                $translator = config('validation.translator');
                $e->setParam('translator', function($message) use($translator) {
                    $language = $translator['lang'];
                    $messages = $translator['messages'];

                    return isset($messages[$message]) ? $messages[$message][$language] : $message;
                });

                $e->findMessages($messages);
                $errors[$field] = $e->getMessages();
            }
        }
        Session::set('errors', $errors);
        return __CLASS__;
    }
616774
public function instance_form_validation(array $data, array $files) : array {

        $errors = parent::instance_form_validation($data, $files);
        $maxlength = $this->get_field()->get_configdata_property('maxlength');
        $elementname = $this->get_form_element_name();
        if (($maxlength > 0) && ($maxlength < \core_text::strlen($data[$elementname]))) {
            $errors[$elementname] = get_string('errormaxlength', 'customfield_text', $maxlength);
        }
        return $errors;
    }
600910
public function validate($values) {
    $errors = array();
    $warnings = array();
    $tokens = array();

    $has_drupal_acct_prov_servers  = (boolean)($this->drupalAcctProvisionServer);
    $has_drupal_acct_prov_settings_options  = (count(array_filter($this->drupalAcctProvisionTriggers)) > 0);

    if (!$has_drupal_acct_prov_servers && $has_drupal_acct_prov_settings_options) {
      $warnings['drupalAcctProvisionServer'] =  t('No Servers are enabled to provide provisioning to Drupal, but Drupal Account Provisioning Options are selected.', $tokens);
    }
    if ($has_drupal_acct_prov_servers && !$has_drupal_acct_prov_settings_options) {
      $warnings['drupalAcctProvisionTriggers'] =  t('Servers are enabled to provide provisioning to Drupal, but no Drupal Account Provisioning Options are selected.  This will result in no synching happening.', $tokens);
    }

    $has_ldap_prov_servers = (boolean)($this->ldapEntryProvisionServer);
    $has_ldap_prov_settings_options = (count(array_filter($this->ldapEntryProvisionTriggers)) > 0);
    if (!$has_ldap_prov_servers && $has_ldap_prov_settings_options) {
      $warnings['ldapEntryProvisionServer'] =  t('No Servers are enabled to provide provisioning to ldap, but LDAP Entry Options are selected.', $tokens);
    }
    if ($has_ldap_prov_servers && !$has_ldap_prov_settings_options) {
      $warnings['ldapEntryProvisionTriggers'] =  t('Servers are enabled to provide provisioning to ldap, but no LDAP Entry Options are selected.  This will result in no synching happening.', $tokens);
    }

    if (isset($this->ldapUserSynchMappings)) {
      $to_ldap_entries_mappings_exist = FALSE;
      foreach ($this->ldapUserSynchMappings as $synch_direction => $mappings) {
        $map_index = array();
        $tokens = array(); // array('%sid' => $sid);
        $to_drupal_user_mappings_exist = FALSE;
        $to_ldap_entries_mappings_exist = FALSE;

        foreach ($mappings as $target_attr => $mapping) {
          if ($mapping['direction'] == LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER) {
            $attr_value = $mapping['user_attr'];
            $attr_name = 'user_attr';
          }
          if ($mapping['direction'] == LDAP_USER_PROV_DIRECTION_TO_LDAP_ENTRY) {
            $attr_value = $mapping['ldap_attr'];
            $attr_name = 'ldap_attr';
          }
          foreach ($values as $field => $value) {
            $parts = explode('__', $field);
            if (count($parts) == 4 && $parts[2] == $attr_name && $value == $attr_value) {
              $map_index[$attr_value] = $parts[3];
            }
          }
        }

        foreach ($mappings as $target_attr => $mapping) {
          foreach ($mapping as $key => $value) {
            if (is_scalar($value)) {
              $tokens['%' . $key] = $value;
            }
          }
          $row_descriptor = t("server %sid row mapping to ldap attribute %ldap_attr", $tokens);
          $tokens['!row_descriptor'] = $row_descriptor;
          $ldap_attribute_maps_in_token = array();
         // debug('calling ldap_servers_token_extract_attributes from validate, mapping='); debug($mapping['ldap_attr']);
          ldap_servers_token_extract_attributes($ldap_attribute_maps_in_token, $mapping['ldap_attr']);

          if ($mapping['direction'] == LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER) {
            $row_id = $map_index[$mapping['user_attr']];
            $to_drupal_user_mappings_exist = TRUE;
          //  if (!$is_drupal_user_prov_server) {
           //   $errors['mappings__'. $sid] =  t('Mapping rows exist for provisioning to drupal user, but server %sid is not enabled for provisioning
            //    to drupal users.', $tokens);
          //  }
          }
          if ($mapping['direction'] == LDAP_USER_PROV_DIRECTION_TO_LDAP_ENTRY) {
            $row_id = $map_index[$mapping['ldap_attr']];
            $to_ldap_entries_mappings_exist = TRUE;
           // if (!$is_ldap_entry_prov_server) {
            //  $errors['mappings__'. $sid] =  t('Mapping rows exist for provisioning to ldap entries,
            //    but server %sid is not enabled for provisioning
             //   to ldap entries.', $tokens);
           // }

            if (count(array_keys($ldap_attribute_maps_in_token)) != 1) {
              $token_field_id = join('__', array('sm', 'user_tokens', $row_id));
              $errors[$token_field_id] =  t('When provisioning to ldap, ldap attribute column must be singular token such as [cn]. %ldap_attr is not.
                Do not use compound tokens such as "[displayName] [sn]" or literals such as "physics". Location: !row_descriptor', $tokens);
            }

          }
          $ldap_attr_field_id = join('__', array('sm', 'ldap_attr', $row_id));
          $user_attr_field_id = join('__', array('sm', 'user_attr', $row_id));
          $first_context_field_id = join('__', array('sm', 1, $row_id));
          $user_tokens_field_id = join('__', array('sm', 'user_tokens', $row_id));

          if (!$mapping['ldap_attr']) {
            $errors[$ldap_attr_field_id] =  t('No LDAP Attribute given in !row_descriptor', $tokens);
          }
          if ($mapping['user_attr'] == 'user_tokens' && !$mapping['user_tokens']) {
            $errors[$user_tokens_field_id] =  t('User tokens selected in !row_descriptor, but user tokens column empty.', $tokens);
          }

          if (isset($mapping['prov_events']) && count($mapping['prov_events']) == 0) {
            $warnings[$first_context_field_id] =  t('No synchronization events checked in !row_descriptor.
              This field will not be synchronized until some are checked.', $tokens);
          }
        }
      }
      if ($to_ldap_entries_mappings_exist && !isset($mappings['[dn]'])) {
        $errors['mappings__' . $synch_direction] =  t('Mapping rows exist for provisioning to ldap, but no ldap attribute is targetted for [dn].
          One row must map to [dn].  This row will have a user token like cn=[property.name],ou=users,dc=ldap,dc=mycompany,dc=com');
      }
    }
    return array($errors, $warnings);
  }
695265
public function validation($data, $files) {
        $errors = [];
        if (isset($data['purgeselectedcaches']) && empty(array_filter($data['purgeselectedoptions']))) {
            $errors['purgeselectedoptions'] = get_string('purgecachesnoneselected', 'admin');
        }
        return $errors;
    }
980588
public function submitForm(array $values)
    {
        $this->value = isset($values[$this->name]) ? $values[$this->name] : null;
    }
719671
protected function validate_uploaded_file($data, $errors) {
        if (empty($data['newfile'])) {
            $errors['newfile'] = get_string('required');
            return $errors;
        }

        $files = $this->get_draft_files('newfile');
        if (count($files) < 1) {
            $errors['newfile'] = get_string('required');
            return $errors;
        }

        if (empty($data['format'])) {
            $errors['format'] = get_string('required');
            return $errors;
        }

        $formatfile = 'format/' . $data['format'] . '/format.php';
        if (!is_readable($formatfile)) {
            throw new moodle_exception('formatnotfound', 'question', '', $data['format']);
        }

        require_once($formatfile);

        $classname = 'qformat_' . $data['format'];
        $qformat = new $classname();

        $file = reset($files);
        if (!$qformat->can_import_file($file)) {
            $a = new stdClass();
            $a->actualtype = $file->get_mimetype();
            $a->expectedtype = $qformat->mime_type();
            $errors['newfile'] = get_string('importwrongfiletype', 'question', $a);
        }

        return $errors;
    }
324468
protected function getAuthenticationForm($values = array())
    {
        $form = new Form();
        $form->setMethod('POST');
        $form->setAction(PHPCI_URL . 'settings/authentication');
        $form->addField(new Form\Element\Csrf('csrf'));

        $field = new Form\Element\Checkbox('disable_authentication');
        $field->setCheckedValue(1);
        $field->setRequired(false);
        $field->setClass('ml20px');
        $field->setLabel('Disable Authentication?');
        $field->setContainerClass('form-group');
        $field->setValue(0);

        if (isset($values['state'])) {
            $field->setValue((int)$values['state']);
        }

        $form->addField($field);

        $field = new Form\Element\Submit();
        $field->setValue('Save &raquo;');
        $field->setClass('btn btn-success pull-right');
        $form->addField($field);

        $form->setValues($values);

        return $form;
    }
309714
protected function checkSubmit($storage)
    {
        if ($this->isFormSubmitted($this->request) && $this->isSubmitAllowed()) {
            $postValues = $this->getPostValues($this->request);
            $this->setUserSessionBackup();
            $storage->getDocuments()->addDocument($postValues);
            $this->restoreUserSessionBackup();
            $this->setSubmitToSession();
            $this->postSubmit($postValues, $storage);
        }
    }
188790
public function check(array $required, array $values)
	{
		foreach ($required as $key)
		{
			if (!array_key_exists($key, $values))
			{
				return false;
			}
		}

		return true;
	}
575968
public function validate(array $values, array $rules)
    {
        // Assume no validation and result success
        $result = true;

        if (true !== $valid = $this->validateByRules($rules, $values)) {
            foreach ($valid as $componentName => $error) {
                $this->setError($error, $componentName);
            }

            // Set general form error
            $this->setError(
                [
                    'error' => 'general',
                    'info'  => [],
                ],
                Doozr_Form_Service_Constant::ERROR_IDENTIFIER_FORM
            );

            $result = false;
        }

        return $result;
    }