Custom form validation

@param array $data
@param array $files
@return array
347858
public function validation($data, $files) {
        $errors = parent::validation($data, $files);

        if (isset($data['rawname'])) {
            $newname = core_text::strtolower($data['rawname']);
            $tag = $this->_customdata['tag'];
            if ($tag->name != $newname) {
                // The name has changed, let's make sure it's not another existing tag.
                if (core_tag_tag::get_by_name($tag->tagcollid, $newname)) {
                    // Something exists already, so flag an error.
                    $errors['rawname'] = get_string('namesalreadybeeingused', 'tag');
                }
            }
        }

        return $errors;
    }
1326200
public function instance_form_validation(array $data, array $files) : array {
        $errors = parent::instance_form_validation($data, $files);

        $elementname = $this->get_form_element_name();
        if (!empty($data[$elementname])) {
            // Compare the date with min/max values, trim the date to the minute or to the day (depending on inludetime setting).
            $includetime = $this->get_field()->get_configdata_property('includetime');
            $machineformat = $includetime ? '%Y-%m-%d %H:%M' : '%Y-%m-%d';
            $humanformat = $includetime ? get_string('strftimedatetimeshort') : get_string('strftimedatefullshort');
            $value = userdate($data[$elementname], $machineformat, 99, false, false);
            $mindate = $this->get_field()->get_configdata_property('mindate');
            $maxdate = $this->get_field()->get_configdata_property('maxdate');

            if ($mindate && userdate($mindate, $machineformat, 99, false, false) > $value) {
                $errors[$elementname] = get_string('errormindate', 'customfield_date', userdate($mindate, $humanformat));
            }
            if ($maxdate && userdate($maxdate, $machineformat, 99, false, false) < $value) {
                $errors[$elementname] = get_string('errormaxdate', 'customfield_date', userdate($maxdate, $humanformat));
            }
        }

        return $errors;
    }
358136
public function update(array $data, array $files = [])
    {
        if ($data) {
            $blueprint = $this->getBlueprint();

            // Process updated data through the object filters.
            $this->filterElements($data);

            // Get currently stored data.
            $elements = $this->getElements();

            // Merge existing object to the test data to be validated.
            $test = $blueprint->mergeData($elements, $data);

            // Validate and filter elements and throw an error if any issues were found.
            $blueprint->validate($test + ['storage_key' => $this->getStorageKey(), 'timestamp' => $this->getTimestamp()]);
            $data = $blueprint->filter($data, false, true);

            // Finally update the object.
            foreach ($blueprint->flattenData($data) as $key => $value) {
                if ($value === null) {
                    $this->unsetNestedProperty($key);
                } else {
                    $this->setNestedProperty($key, $value);
                }
            }

            // Store the changes
            $this->_changes = Utils::arrayDiffMultidimensional($this->getElements(), $elements);
        }

        if ($files && method_exists($this, 'setUpdatedMedia')) {
            $this->setUpdatedMedia($files);
        }

        return $this;
    }
68250
public function validation($data, $files) {
        global $DB;
        $errors = array();

        // Check course doesn't already exist.
        if (!empty($data['shortname'])) {
            // Check shortname.
            $error = tool_generator_course_backend::check_shortname_available($data['shortname']);
            if ($error) {
                $errors['shortname'] = $error;
            }
        }

        return $errors;
    }
482887
public function validation($data, $files) {
        global $DB;

        $errors = parent::validation($data, $files);
        $eventtype = isset($data['eventtype']) ? $data['eventtype'] : null;
        $coursekey = ($eventtype == 'group') ? 'groupcourseid' : 'courseid';
        $courseid = (!empty($data[$coursekey])) ? $data[$coursekey] : null;
        $eventtypes = calendar_get_allowed_event_types($courseid);

        if (empty($eventtype) || !isset($eventtypes[$eventtype]) || $eventtypes[$eventtype] == false) {
            $errors['eventtype'] = get_string('invalideventtype', 'calendar');
        }

        if ($courseid && $courseid > 0) {
            if ($course = $DB->get_record('course', ['id' => $courseid])) {
                if ($data['timestart'] < $course->startdate) {
                    $errors['timestart'] = get_string('errorbeforecoursestart', 'calendar');
                }
            } else {
                $errors[$coursekey] = get_string('invalidcourse', 'error');
            }
        }

        if ($eventtype == 'course' && empty($courseid)) {
            $errors['courseid'] = get_string('selectacourse');
        }

        if ($eventtype == 'group' && (!empty($courseid) && empty($data['groupid']))) {
            $errors['groupcourseid'] = get_string('nogroups', 'core_group');
        }

        if ($eventtype == 'group' && empty($courseid)) {
            $errors['groupcourseid'] = get_string('selectacourse');
        }

        if ($data['duration'] == 1 && $data['timestart'] > $data['timedurationuntil']) {
            $errors['durationgroup'] = get_string('invalidtimedurationuntil', 'calendar');
        } else if ($data['duration'] == 2 && (trim($data['timedurationminutes']) == '' || $data['timedurationminutes'] < 1)) {
            $errors['durationgroup'] = get_string('invalidtimedurationminutes', 'calendar');
        }

        return $errors;
    }
1008651
function validation($data, $files) {
        global $CFG, $COURSE;
        $errors = parent::validation($data, $files);

        if ($data['allocateby'] != 'no') {
            $source = array();
            if ($data['cohortid']) {
                $source['cohortid'] = $data['cohortid'];
            }
            if ($data['groupingid']) {
                $source['groupingid'] = $data['groupingid'];
            }
            if ($data['groupid']) {
                $source['groupid'] = $data['groupid'];
            }
            if (!$users = groups_get_potential_members($data['courseid'], $data['roleid'], $source)) {
                $errors['roleid'] = get_string('nousersinrole', 'group');
            }

           /// Check the number entered is sane
            if ($data['groupby'] == 'groups') {
                $usercnt = count($users);

                if ($data['number'] > $usercnt || $data['number'] < 1) {
                    $errors['number'] = get_string('toomanygroups', 'group', $usercnt);
                }
            }
        }

        //try to detect group name duplicates
        $name = groups_parse_name(trim($data['namingscheme']), 0);
        if (groups_get_group_by_name($COURSE->id, $name)) {
            $errors['namingscheme'] = get_string('groupnameexists', 'group', $name);
        }

        // check grouping name duplicates
        if ( isset($data['grouping']) && $data['grouping'] == '-1') {
            $name = trim($data['groupingname']);
            if (empty($name)) {
                $errors['groupingname'] = get_string('required');
            } else if (groups_get_grouping_by_name($COURSE->id, $name)) {
                $errors['groupingname'] = get_string('groupingnameexists', 'group', $name);
            }
        }

       /// Check the naming scheme
        if ($data['groupby'] == 'groups' and $data['number'] == 1) {
            // we can use the name as is because there will be only one group max
        } else {
            $matchcnt = preg_match_all('/[#@]{1,1}/', $data['namingscheme'], $matches);
            if ($matchcnt != 1) {
                $errors['namingscheme'] = get_string('badnamingscheme', 'group');
            }
        }

        return $errors;
    }
27521
public function multipart(array $data = [], $files = false) {

        if(is_array($files)) {

            foreach($files as $name => $file) {

                $data[$name] = $this->file($file);

            }

        }

        $this->params = $data;

        return $this->header(['Content-Type' => 'multipart/form-data']);
    }
708332
public function validate(array $data)
    {
        $rules = $this->getRules();
        foreach ($rules as $field => $rule) {
            if ((isset($rule['required']) && $rule['required'] === true && isset($data[$field]))
                || ((!isset($rule['required']) || !$rule['required'])) && isset($data[$field])) {
                foreach ($rule as $key => $value) {
                    if ($key !== 'required') {
                        foreach ($value as $validator) {
                            if (!is_array($validator)) {
                                $validator = [$validator];
                            }
                            if (!Validator::validate($validator[0], $field,
                                    $data, $validator)) {
                                $this->addError($field,
                                    isset($rule['errorMessage']) ? $rule['errorMessage']
                                            : false);
                            }
                        }
                    }
                }
            } elseif (isset($rule['required']) && $rule['required'] === true) {
                $this->addError($field,
                    isset($rule['errorMessage']) ? $rule['errorMessage'] : false);
            }
        }
        return !$this->hasErrors();
    }
1196557
private function isValidFileList(array $files)
    {
        Assertion::notEmpty($files, 'Files array can\'t be empty');

        $valid = false;

        foreach ($files as $file) {
            if ($this->isFileExisting($file)) {
                $valid = true;
            }
        }

        return $valid;
    }
1277337
public function define_validate_specific($data, $files) {
        $errors = array();

        // Make sure the start year is not greater than the end year.
        if ($data->param1 > $data->param2) {
            $errors['param1'] = get_string('startyearafterend', 'profilefield_datetime');
        }

        return $errors;
    }
1154457
public function validation($data, $files) {
        global $DB;
        $errors = array();
        $plugin = $this->_customdata['plugin'];
        $instance = (isset($this->_customdata['instance'])
                && is_subclass_of($this->_customdata['instance'], 'repository'))
            ? $this->_customdata['instance'] : null;

        if (!$instance) {
            $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
        } else {
            $errors = $instance->instance_form_validation($this, $data, $errors);
        }

        $sql = "SELECT count('x')
                  FROM {repository_instances} i, {repository} r
                 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
        $params = array('name' => $data['name'], 'plugin' => $this->plugin, 'contextid' => $this->contextid);
        if ($instance) {
            $sql .= ' AND i.id != :instanceid';
            $params['instanceid'] = $instance->id;
        }
        if ($DB->count_records_sql($sql, $params) > 0) {
            $errors['name'] = get_string('erroruniquename', 'repository');
        }

        return $errors;
    }
892857
public function validation($data, $files) {
        $errors = parent::validation($data, $files);

        if (!empty($data['timesplitting'])) {
            $realtimesplitting = \tool_analytics\output\helper::option_to_class($data['timesplitting']);
            if (\core_analytics\manager::is_valid($realtimesplitting, '\core_analytics\local\time_splitting\base') === false) {
                $errors['timesplitting'] = get_string('errorinvalidtimesplitting', 'analytics');
            }
        }

        if (!$this->_customdata['staticmodel']) {
            if (empty($data['indicators'])) {
                $errors['indicators'] = get_string('errornoindicators', 'analytics');
            } else {
                foreach ($data['indicators'] as $indicator) {
                    $realindicatorname = \tool_analytics\output\helper::option_to_class($indicator);
                    if (\core_analytics\manager::is_valid($realindicatorname, '\core_analytics\local\indicator\base') === false) {
                        $errors['indicators'] = get_string('errorinvalidindicator', 'analytics', $realindicatorname);
                    }
                }
            }
        }

        if (!empty($data['enabled']) && empty($data['timesplitting'])) {
            $errors['enabled'] = get_string('errorcantenablenotimesplitting', 'tool_analytics');
        }

        return $errors;
    }
586677
protected function validateUploads(array $files): void
    {
        foreach ($files as $file) {
            if (null === $file) {
                continue;
            }
            if ($file instanceof UploadedFileInterface) {
                $this->validateUpload($file);
            } else {
                $this->validateUploads($file);
            }
        }
    }
676552
public function validation($data, $files) {
        $errors = parent::validation($data, $files);

        if (!empty($data['allowsubmissionsfromdate']) && !empty($data['duedate'])) {
            if ($data['duedate'] < $data['allowsubmissionsfromdate']) {
                $errors['duedate'] = get_string('duedatevalidation', 'assign');
            }
        }
        if (!empty($data['cutoffdate']) && !empty($data['duedate'])) {
            if ($data['cutoffdate'] < $data['duedate'] ) {
                $errors['cutoffdate'] = get_string('cutoffdatevalidation', 'assign');
            }
        }
        if (!empty($data['allowsubmissionsfromdate']) && !empty($data['cutoffdate'])) {
            if ($data['cutoffdate'] < $data['allowsubmissionsfromdate']) {
                $errors['cutoffdate'] = get_string('cutoffdatefromdatevalidation', 'assign');
            }
        }
        if ($data['gradingduedate']) {
            if ($data['allowsubmissionsfromdate'] && $data['allowsubmissionsfromdate'] > $data['gradingduedate']) {
                $errors['gradingduedate'] = get_string('gradingduefromdatevalidation', 'assign');
            }
            if ($data['duedate'] && $data['duedate'] > $data['gradingduedate']) {
                $errors['gradingduedate'] = get_string('gradingdueduedatevalidation', 'assign');
            }
        }
        if ($data['blindmarking'] && $data['attemptreopenmethod'] == ASSIGN_ATTEMPT_REOPEN_METHOD_UNTILPASS) {
            $errors['attemptreopenmethod'] = get_string('reopenuntilpassincompatiblewithblindmarking', 'assign');
        }

        return $errors;
    }
90293
public function validation($data, $files) {
        global $DB;

        $errors = array();
        if ($DB->count_records('portfolio_instance', array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
            $errors = array('name' => get_string('err_uniquename', 'portfolio'));
        }

        $pluginerrors = array();
        $pluginerrors = portfolio_static_function($this->plugin, 'admin_config_validation', $data);
        if (is_array($pluginerrors)) {
            $errors = array_merge($errors, $pluginerrors);
        }
        return $errors;
    }
380658
public function validation($data, $files) {
        global $CFG, $DB;
        $errors = parent::validation($data, $files);

        $data  = (object)$data;

        $duplicate = $DB->get_field('user_info_category', 'id', array('name' => $data->name));

        // Check the name is unique.
        if (!empty($data->id)) { // We are editing an existing record.
            $olddata = $DB->get_record('user_info_category', array('id' => $data->id));
            // Name has changed, new name in use, new name in use by another record.
            $dupfound = (($olddata->name !== $data->name) && $duplicate && ($data->id != $duplicate));
        } else { // New profile category.
            $dupfound = $duplicate;
        }

        if ($dupfound ) {
            $errors['name'] = get_string('profilecategorynamenotunique', 'admin');
        }

        return $errors;
    }
1019433
public function validation($data, $files) {
        $errors = parent::validation($data, $files);

        // check the phases borders are valid
        if ($data['submissionstart'] > 0 and $data['submissionend'] > 0 and $data['submissionstart'] >= $data['submissionend']) {
            $errors['submissionend'] = get_string('submissionendbeforestart', 'mod_workshop');
        }
        if ($data['assessmentstart'] > 0 and $data['assessmentend'] > 0 and $data['assessmentstart'] >= $data['assessmentend']) {
            $errors['assessmentend'] = get_string('assessmentendbeforestart', 'mod_workshop');
        }

        // check the phases do not overlap
        if (max($data['submissionstart'], $data['submissionend']) > 0 and max($data['assessmentstart'], $data['assessmentend']) > 0) {
            $phasesubmissionend = max($data['submissionstart'], $data['submissionend']);
            $phaseassessmentstart = min($data['assessmentstart'], $data['assessmentend']);
            if ($phaseassessmentstart == 0) {
                $phaseassessmentstart = max($data['assessmentstart'], $data['assessmentend']);
            }
            if ($phasesubmissionend > 0 and $phaseassessmentstart > 0 and $phaseassessmentstart < $phasesubmissionend) {
                foreach (array('submissionend', 'submissionstart', 'assessmentstart', 'assessmentend') as $f) {
                    if ($data[$f] > 0) {
                        $errors[$f] = get_string('phasesoverlap', 'mod_workshop');
                        break;
                    }
                }
            }
        }

        // Check that the submission grade pass is a valid number.
        if (!empty($data['submissiongradepass'])) {
            $submissiongradefloat = unformat_float($data['submissiongradepass'], true);
            if ($submissiongradefloat === false) {
                $errors['submissiongradepass'] = get_string('err_numeric', 'form');
            } else {
                if ($submissiongradefloat > $data['grade']) {
                    $errors['submissiongradepass'] = get_string('gradepassgreaterthangrade', 'grades', $data['grade']);
                }
            }
        }

        // Check that the grade pass is a valid number.
        if (!empty($data['gradinggradepass'])) {
            $gradepassfloat = unformat_float($data['gradinggradepass'], true);
            if ($gradepassfloat === false) {
                $errors['gradinggradepass'] = get_string('err_numeric', 'form');
            } else {
                if ($gradepassfloat > $data['gradinggrade']) {
                    $errors['gradinggradepass'] = get_string('gradepassgreaterthangrade', 'grades', $data['gradinggrade']);
                }
            }
        }

        if (!$data['submissiontypetextavailable'] && !$data['submissiontypefileavailable']) {
            // One submission type must be available.
            $errors['submissiontypes'] = get_string('nosubmissiontype', 'workshop');
        }

        return $errors;
    }