Custom validations.

@throws \coding_exception
@return void
161208
protected function validate_data() {
        parent::validate_data();

        if (!isset($this->objectid)) {
            throw new \coding_exception('The \'objectid\' must be set.');
        }
        if (!isset($this->other['badgetype'])) {
            throw new \coding_exception('The \'badgetype\' value must be set in other.');
        } else {
            if (($this->other['badgetype'] != BADGE_TYPE_COURSE) && ($this->other['badgetype'] != BADGE_TYPE_SITE)) {
                throw new \coding_exception('Invalid \'badgetype\' value.');
            }
        }
        if ($this->other['badgetype'] == BADGE_TYPE_COURSE) {
            if (!isset($this->other['courseid'])) {
                throw new \coding_exception('The \'courseid\' value must be set in other.');
            }
        }
    }
1167902
protected function validate() {
        $c = strlen($this->text);
        if ($c === 0) {
            throw new CINParseException('codabar', 'No data has been entered.');
        }

        // Checking if all chars are allowed
        for ($i = 0; $i < $c; $i++) {
            if (array_search($this->text[$i], $this->keys) === false) {
                throw new CINParseException('codabar', 'The character \'' . $this->text[$i] . '\' is not allowed.');
            }
        }

        // Must start by A, B, C or D
        if ($c == 0 || ($this->text[0] !== 'A' && $this->text[0] !== 'B' && $this->text[0] !== 'C' && $this->text[0] !== 'D')) {
            throw new CINParseException('codabar', 'The text must start by the character A, B, C, or D.');
        }

        // Must end by A, B, C or D
        $c2 = $c - 1;
        if ($c2 === 0 || ($this->text[$c2] !== 'A' && $this->text[$c2] !== 'B' && $this->text[$c2] !== 'C' && $this->text[$c2] !== 'D')) {
            throw new CINParseException('codabar', 'The text must end by the character A, B, C, or D.');
        }

        parent::validate();
    }
677450
private function validate()
    {
        if (!class_exists($this->class)) {
            throw new \RuntimeException(sprintf('Class %s does not exist, is this the correct namespace?', $this->class));
        }
        if (!in_array($this->method, get_class_methods($this->class))) {
            throw new \RuntimeException(sprintf('The method "%s" does not exist in "%s" class.', $this->method, $this->class));
        }
    }
519431
protected function make_fields_validation() {
		foreach ( $this->fields as $key => $field ) {
			if ( $this->maybe_skip_field( $field ) ) {
				continue;
			}

			if ( $rules = $field->get_option( 'validate' ) ) {
				$attributes = ( new Rules_Parser( $field ) )->parse( $rules );
				$field->set_attribute( $attributes );
			}
		}
	}
558202
protected function setupValidations()
    {
        $this->validations->of(
            TransactionType::CAPTURE |
            TransactionType::EDIT |
            TransactionType::HOLD |
            TransactionType::RELEASE
        )
            ->check('transactionId')->isNotNull();

        $this->validations->of(TransactionType::EDIT)
            ->with(TransactionModifier::LEVEL_II)
            ->check('taxType')->isNotNull();

        $this->validations->of(TransactionType::REFUND)
            ->when('amount')->isNotNull()
            ->check('currency')->isNotNull();

        $this->validations->of(TransactionType::VERIFY_SIGNATURE)
            ->check('payerAuthenticationResponse')->isNotNull()
            ->check('amount')->isNotNull()
            ->check('currency')->isNotNull()
            ->check('orderId')->isNotNull();
    }
920094
protected function prepareForValidation(): void
    {
        $data = $this->all();

        // Set abilities
        if (! empty($data['abilities'])) {
            if ($this->user($this->route('guard'))->can('grant', \Cortex\Auth\Models\Ability::class)) {
                $abilities = array_map('intval', $this->get('abilities', []));
                $data['abilities'] = $this->user($this->route('guard'))->isA('superadmin') ? $abilities
                    : $this->user($this->route('guard'))->getAbilities()->pluck('id')->intersect($abilities)->toArray();
            } else {
                unset($data['abilities']);
            }
        }

        $this->replace($data);
    }
478143
public function setupRules()
    {
        parent::setupRules();

        $this->rules->validator = new Validator(
            ['!format.block.code', '!format.monospace', '!operator.escape', '!operator', '!tag']
        );

        $this->rules->addMany([
            'format.header' => [
                new Rule(new RegexMatcher('/^\s{0,3}(#+.+?)\r?$/m')),
                new Rule(new RegexMatcher('/^([^\r\n]+?)^(?:-+|=+)\R?$/m'))
            ],
            'format.italics'   => new Rule(
                new RegexMatcher('/(?:^|[^*_])(?P<italics>(?P<i>[*_])(?>[^*_\r\n]|(?:(?P<b>[*_]{2})(?>[^*_\r\n]|(?&italics))*?\g{b}))+\g{i})/'), [
                    'italics' => Token::NAME
                ]
            ),
            'format.bold'  => new Rule(
                new RegexMatcher('/(?P<bold>(?P<b>\*\*|__)(?>[^*_\r\n]|(?:(?P<i>[*_]{2})(?>[^*_\r\n]|(?&bold))*?\g{i}))+\g{b})/', [
                    'bold' => Token::NAME
                ])
            ),
            'format.strike'    => new Rule(new RegexMatcher('/(~~.+?~~)/')),
            'format.monospace' => [
                new Rule(new RegexMatcher('/(?:[^`]|^)(`.*?`)/')),
                new Rule(new RegexMatcher('/(``.*?``)/')),
                new Rule(new RegexMatcher('/^((?:(?: {4,}|\t).*?(?>\R|$)+?)+)/m')),
            ],

            'operator.list.ordered'   => new Rule(new RegexMatcher('/^\s*(\d+[.)])/m')),
            'operator.list.unordered' => new Rule(new RegexMatcher('/^\s*([-+*])/m'), [
                'context' => ['none'],
                'priority' => 1
            ]),

            'string.quote'       => new Rule(new RegexMatcher('/((?:^>.*?\R)+)/m')),
            'format.block.code'  => [
                new Rule(
                    new DelegateRegexMatcher(
                        '/^```(.*?)\R(.*?)\R^```/ms',
                        function($match, TokenFactoryInterface $factory) {
                            $lang = KeyLighter::get()->getLanguage($match[1][0]);
                            yield $factory->create(Token::NAME, ['pos' => $match[0][1], 'length' => strlen($match[0][0])]);
                            yield $factory->create(
                                "language.{$lang->getIdentifier()}", [
                                    'pos'    => $match[2][1],
                                    'length' => strlen($match[2][0]),
                                    'inject' => $lang,
                                    'class'  => LanguageToken::class,
                                ]
                            );
                        }
                    ), [
                        'context'     => Validator::everywhere(),
                        'postProcess' => true,
                        'priority'    => 1000
                    ]
                ),
            ],

            'operator.escape' => new Rule(new RegexMatcher('/(\\\.)/')),

            'operator.horizontal' => new Rule(new RegexMatcher('/^\s{,3}(([-*_])( ?\2)+)\R/m'), [
                'priority' => 2
            ]),

            'symbol.link'  => new Rule(new RegexMatcher('/[^!](\[(?:[^\[\]]|!\[.*?\]\(.*?\))*\])/i')),
            'symbol.url'   => new Rule(new RegexMatcher('#(<(https?://|[^/])[-A-Za-z0-9+&@\#/%?=~_|!:,.;]+[-A-Za-z0-9+&@\#/%=~_|]>|https?://[-A-Za-z0-9+&@\#/%?=~_|!:,.;]+[-A-Za-z0-9+&@\#/%=~_|])#i'), [
                'priority' => 0,
            ]),
            'symbol.image' => new Rule(new RegexMatcher('/(!)(\[.*?\])\(.*?\)/i', [
                1 => 'operator.image',
                2 => '$.title',
            ])),
        ]);
    }
1262864
public function validate() : void
    {
        if (null === $this->is_valid) {
            if (null === $this->user_value && null !== $this->default_value) {
                // There is a preset value, and its not being changed
                $this->is_valid = true;
            } elseif (null != $this->validator && false != $this->validator) {
                if ('' === $this->user_value && false === $this->required) {
                    $this->is_valid = true;
                    return;
                } elseif ('' === $this->user_value && true === $this->required) {
                    $this->is_valid = false;
                    return;
                }
                try {
                    $validator = $this->validator;
                    $result = $validator::quickValidate($this->user_value, $this->constraints);
                    $this->user_value = $result;
                    $this->is_valid = true;
                } catch (InvalidInputException $e) {
                    $this->user_value = null;
                    $this->is_valid = false;
                    $this->error = $e->getMessage();
                }

            } else {
                // This field does not get validated
                $this->is_valid = true;
            }
        }
        // Check if the input is different from the default value
        if ($this->is_valid && null !== $this->user_value) {
            $this->is_changed = ($this->default_value != $this->user_value);
        }
    }
481405
protected function validate()
	{
		$this->loadXML();
		$this->id = $this->xml->firstChild->nextSibling->getAttribute('id');
		$this->detectAutoValidate();

		$this->validateInputs($this->xml->firstChild->nextSibling);
	}
1270884
protected function validateFromAttributes()
    {
        $value = $this->attribs['value'];
        if (\strlen($value) == 0) {
            $this->debug->log('empty value');
            if ($this->isRequired()) {
                $this->flag();
            }
        } elseif (isset($this->attribs['pattern']) && !\preg_match('/^'.\str_replace('/', '\/', $this->attribs['pattern']).'$/', $value)) {
            $this->debug->log('pattern mismatch');
            $this->flag('invalid format');
        } elseif (isset($this->attribs['max']) && \preg_replace('/[^-\d\.]/', '', $value) > $this->attribs['max']) {
            $this->debug->log('too big');
            $this->flag('value is too large');
        } elseif (isset($this->attribs['min']) && \preg_replace('/[^-\d\.]/', '', $value) < $this->attribs['min']) {
            $this->debug->log('too small');
            $this->flag('value is too small');
        } elseif (isset($this->attribs['maxlength']) && \mb_strlen($value) > $this->attribs['maxlength']) {
            $this->debug->log('too long');
            if (empty($this->props['invalidReason'])) {
                $this->props['invalidReason'] = 'Value is too long';
            }
            $this->flag($this->props['invalidReason']);
        }
    }
444469
public function definition() {
        global $PAGE;
        $mform = $this->_form;

        $field = $this->_customdata['field'];
        if (!($field && $field instanceof field_controller)) {
            throw new \coding_exception('Field must be passed in customdata');
        }
        $handler = $field->get_handler();

        $mform->addElement('header', '_commonsettings', get_string('commonsettings', 'core_customfield'));

        $mform->addElement('text', 'name', get_string('fieldname', 'core_customfield'), 'size="50"');
        $mform->addRule('name', null, 'required', null, 'client');
        $mform->setType('name', PARAM_TEXT);

        // Accepted values for 'shortname' would follow [a-z0-9_] pattern,
        // but we are accepting any PARAM_TEXT value here,
        // and checking [a-zA-Z0-9_] pattern in validation() function to throw an error when needed.
        $mform->addElement('text', 'shortname', get_string('fieldshortname', 'core_customfield'), 'size=20');
        $mform->addHelpButton('shortname', 'shortname', 'core_customfield');
        $mform->addRule('shortname', null, 'required', null, 'client');
        $mform->setType('shortname', PARAM_TEXT);

        $desceditoroptions = $handler->get_description_text_options();
        $mform->addElement('editor', 'description_editor', get_string('description', 'core_customfield'), null, $desceditoroptions);
        $mform->addHelpButton('description_editor', 'description', 'core_customfield');

        // If field is required.
        $mform->addElement('selectyesno', 'configdata[required]', get_string('isfieldrequired', 'core_customfield'));
        $mform->addHelpButton('configdata[required]', 'isfieldrequired', 'core_customfield');
        $mform->setType('configdata[required]', PARAM_BOOL);

        // If field data is unique.
        $mform->addElement('selectyesno', 'configdata[uniquevalues]', get_string('isdataunique', 'core_customfield'));
        $mform->addHelpButton('configdata[uniquevalues]', 'isdataunique', 'core_customfield');
        $mform->setType('configdata[uniquevalues]', PARAM_BOOL);

        // Field specific settings from field type.
        $field->config_form_definition($mform);

        // Handler/component settings.
        $handler->config_form_definition($mform);

        // We add hidden fields.
        $mform->addElement('hidden', 'categoryid');
        $mform->setType('categoryid', PARAM_INT);

        $mform->addElement('hidden', 'type');
        $mform->setType('type', PARAM_COMPONENT);

        $mform->addElement('hidden', 'id');
        $mform->setType('id', PARAM_INT);

        $this->add_action_buttons(true);
    }
1263436
protected function validateEditField()
    {
        $this->setSubmitted('field');
        $this->setSubmitted('update', $this->data_field);

        $this->validateComponent('field');

        return !$this->hasErrors();
    }
562535
protected function before_validate() {
        $this->beforeupdate = null;

        // During update.
        if ($this->get('id')) {
            $this->beforeupdate = new self($this->get('id'));
        }
    }
1014511
private function validate()
    {
        $required = '';

        $validations = [
            'FirstnameOrLastname',
            'PhoneCellphoneOrEmail',
            'ContactTypeId',
            'BusinessTypeId',
            'SuboriginId',
        ];

        for ($i = 0; $i < count($validations) && empty($required); $i++) {
            $required = $this->{"validate" . $validations[$i]}();
        }

        if (!empty($required)) {
            throw new InvalidArgumentException(
                sprintf('Missing required value: %s.', $required)
            );
        }
    }
484138
protected function validateRanges()
    {
        if (!$this->isStartTimeValid()) {
            $message = sprintf(
                Swat::_(
                    'The time you have entered is invalid. ' .
                        'It must be on or after %s.'
                ),
                $this->getFormattedTime($this->valid_range_start)
            );

            $this->addMessage(new SwatMessage($message, 'error'));
        } elseif (!$this->isEndTimeValid()) {
            $message = sprintf(
                Swat::_(
                    'The time you have entered is invalid. ' .
                        'It must be on or before %s.'
                ),
                $this->getFormattedTime($this->valid_range_end)
            );

            $this->addMessage(new SwatMessage($message, 'error'));
        }
    }
463354
public function beforeValidate()
    {
        foreach ($this->attributes as $attribute) {
            $this->owner->$attribute = HtmlPurifier::process($this->owner->$attribute, $this->config);
        }
    }
977257
protected function validate_ranges() {
        foreach ($this->ranges as $key => $range) {
            if (!isset($this->ranges[$key]['start']) || !isset($this->ranges[$key]['end']) ||
                    !isset($this->ranges[$key]['time'])) {
                throw new \coding_exception($this->get_id() . ' time splitting method "' . $key .
                    '" range is not fully defined. We need a start timestamp and an end timestamp.');
            }
        }
    }