validate/rules
<

return function () {
    $self = url('/@object/@action/' . urlencode('validate/rules'));
    $sample = _class('docs')->_sample('validate_rules');
    $preset = is_string($_GET['preset'] ?? null) && isset($sample->PRESETS[$_GET['preset']]) ? $_GET['preset'] : '';
    $p = $preset !== '' ? $sample->preset($preset) : $sample->params($_GET);
    $submitted = $preset !== '' || isset($_GET['value']);

    $intro = '<p class="docs-demo-intro">' . t('The rules of the framework validator, one by one. Type a value, tick rules and see what each rule says about it, what <code>validate()</code> returns for the whole chain, and the rule string to put into <code>form()->validate()</code>. Preparation rules (<code>trim</code>, <code>strtolower</code>, <code>strip_tags</code>) are PHP functions that change the value the next rules see. Rules and their parameters come from fixed lists, the value is capped at %max characters; rules that query the database or the network or take a regex are not offered. Classes: <code>yf_validate</code>, <code>yf_form2</code>.', ['%max' => $sample->MAX_VALUE_LEN]) . '</p>';

    $presets = '';
    foreach (array_keys($sample->PRESETS) as $name) {
        $presets .= '<a class="btn btn-sm ' . ($name === $preset ? 'btn-primary active' : 'btn-default btn-outline-primary') . '" href="'
            . $self . '?' . _prepare_html(http_build_query(['preset' => $name]), 0) . '">' . _prepare_html($name, 0) . '</a> ';
    }

    $groups = '';
    foreach ($sample->RULES as $group => $rules) {
        $items = '';
        foreach ($rules as $name => $info) {
            [$spec, $hint] = $info;
            $param = $p['params'][$name];
            $input = '';
            if ($spec && $spec[0] === 'choice') {
                $options = '';
                foreach ($spec[1] as $v) {
                    $options .= '<option value="' . _prepare_html($v, 0) . '"' . ($v === $param ? ' selected' : '') . '>' . _prepare_html($v, 0) . '</option>';
                }
                $input = '<select name="p[' . $name . ']" class="form-control form-select form-select-sm input-sm" aria-label="' . $name . ' parameter">' . $options . '</select>';
            } elseif ($spec) {
                $input = '<input type="text" name="p[' . $name . ']" value="' . _prepare_html((string) $param, 0) . '" class="form-control form-control-sm input-sm"'
                    . ' maxlength="13" inputmode="numeric" aria-label="' . $name . ' parameter" title="' . ($spec[0] === 'pair' ? 'min,max: ' : '') . $spec[1] . ' to ' . $spec[2] . '">';
            }
            $items .= '<div class="docs-demo-rule"><label title="' . _prepare_html($hint, 0) . '"><input type="checkbox" name="rules[]" value="' . $name . '"'
                . (array_key_exists($name, $p['rules']) ? ' checked' : '') . '> <code>' . $name . '</code></label>' . $input
                . '</div>';
        }
        $groups .= '<div class="docs-demo-rule-group"><h5>' . _prepare_html(t($group), 0) . '</h5>' . $items . '</div>';
    }

    $results = '';
    if ($submitted && ! $p['rules']) {
        $results = '<div class="alert alert-info">' . t('Tick at least one rule.') . '</div>';
    } elseif ($p['rules']) {
        [$prepared, $each] = $sample->run_each($p);
        [$chain_ok, $chain_error] = $sample->run_chain($p);
        $rows = '';
        $stopped = false;
        foreach ($each as $name => $res) {
            [$ok, $msg] = $res;
            $label = $name . ($p['rules'][$name] !== null ? '[' . $p['rules'][$name] . ']' : '');
            if ($sample->is_prep($name)) {
                $badge = html()->badge(t('prepares'), ['type' => 'info']);
            } else {
                $badge = html()->badge($ok ? t('pass') : t('fail'), ['type' => $ok ? 'success' : 'danger']);
            }
            $note = $stopped ? ' <small class="text-muted">' . t('(the chain stopped before this rule)') . '</small>' : '';
            $rows .= '<tr><td><code>' . _prepare_html($label, 0) . '</code></td><td>' . $badge . '</td><td>' . _prepare_html($msg, 0) . $note . '</td></tr>';
            ! $ok && ! $chain_ok && $stopped = true;
        }
        $has_required = array_key_exists('required', $p['rules']);
        $empty_note = '';
        if ( ! $has_required && trim($prepared) === '') {
            $empty_note = ' ' . t('The value is empty and <code>required</code> is not ticked, so the chain lets it through: an optional field may stay empty.');
        }
        $summary = $chain_ok
            ? '<div class="alert alert-success">' . t('<b>validate() returns true.</b>') . $empty_note . '</div>'
            : '<div class="alert alert-danger">' . t('<b>validate() returns false:</b>') . ' ' . _prepare_html($chain_error, 0) . '</div>';
        $html = _class('html');
        $results = '<div class="' . $html->_ui_or('row', 'row') . ' docs-demo-rules-out"><div class="' . $html->_ui_or('col-md-7', 'col', '7') . '">' . $summary
            . '<p class="docs-demo-value">' . t('Value after preparation: <code>%value</code> (%length characters)', ['%value' => _prepare_html(var_export($prepared, true), 0), '%length' => mb_strlen($prepared)]) . '</p>'
            . '<table class="table table-condensed table-sm table-bordered docs-demo-result"><thead><tr><th>' . t('Rule') . '</th><th>' . t('Result') . '</th><th>' . t('Message') . '</th></tr></thead><tbody>'
            . $rows . '</tbody></table></div>'
            . '<div class="' . $html->_ui_or('col-md-5', 'col', '5') . '"><h4>PHP</h4><pre class="docs-demo-code"><code class="php">' . _prepare_html($sample->code($p), 0) . '</code></pre></div></div>';
    } else {
        $results = '<div class="alert alert-info">' . t('Pick a preset above, or type a value, tick some rules and press <b>Check</b>.') . '</div>';
    }

    $form = '<form method="get" action="' . $self . '" class="docs-demo-rules-form">'
        . '<div class="docs-demo-rules-value"><label for="docs-demo-value">' . t('Value') . '</label>'
        . '<input type="text" id="docs-demo-value" name="value" class="form-control" maxlength="' . $sample->MAX_VALUE_LEN . '" value="' . _prepare_html($p['value'], 0) . '" placeholder="' . t('Type something to validate') . '">'
        . '<button type="submit" class="btn btn-primary">' . t('Check') . '</button> <a class="btn btn-default btn-outline-secondary" href="' . $self . '">' . t('Reset') . '</a></div>'
        . $results . '<h4>' . t('Rules') . '</h4><p class="text-muted">' . t('They run in this order, top to bottom; hover a rule to see what it accepts.') . '</p>'
        . '<div class="docs-demo-rule-groups">' . $groups . '</div><button type="submit" class="btn btn-primary">' . t('Check') . '</button></form>';

    css('.docs-demo-presets { margin-bottom:12px; } .docs-demo-presets .btn { margin:0 4px 4px 0; }
        .docs-demo-rules-value { display:flex; flex-wrap:wrap; align-items:center; gap:8px; margin-bottom:15px; }
        .docs-demo-rules-value label { margin:0; font-weight:bold; }
        .docs-demo-rules-value .form-control { flex:1 1 240px; width:auto; }
        .docs-demo-rule-groups { column-count:3; column-gap:30px; margin-bottom:10px; }
        @media (max-width:991px) { .docs-demo-rule-groups { column-count:2; } }
        @media (max-width:575px) { .docs-demo-rule-groups { column-count:1; } }
        .docs-demo-rule-group { break-inside:avoid; margin-bottom:14px; }
        .docs-demo-rule-group h5 { font-weight:bold; margin:0 0 4px; padding-bottom:3px; border-bottom:1px solid rgba(128,128,128,.3); }
        .docs-demo-rule { display:flex; align-items:center; gap:6px; min-height:26px; }
        .docs-demo-rule label { font-weight:normal; margin:0; white-space:nowrap; cursor:pointer; }
        .docs-demo-rule label input[type=checkbox] { margin:0 3px 0 0; vertical-align:middle; position:static; }
        .docs-demo-rule .form-control { display:inline-block; width:6.5em; height:24px; padding:1px 6px; font-size:12px; line-height:1.4; }
        .docs-demo-rule select.form-control { width:auto; max-width:7.5em; padding-right:22px; background-position:right 4px center; }
        .docs-demo-rules-out .docs-demo-result td { word-break:break-word; }
        @media (min-width:768px) { .docs-demo-rules-out .docs-demo-result td:first-child { white-space:nowrap; } }
        .docs-demo-value code, pre.docs-demo-code code { white-space:pre-wrap; word-break:break-word; }');
    return $intro . '<p class="docs-demo-presets">' . t('Presets:') . ' ' . $presets . '</p>' . $form;
};

Правила валідатора фреймворку, по одному. Введіть значення, позначте правила й подивіться, що кожне правило каже про нього, що validate() повертає для всього ланцюжка, і рядок правил для form()->validate(). Правила підготовки (trim, strtolower, strip_tags) — це функції PHP, що змінюють значення, яке бачать наступні правила. Правила та їхні параметри беруться з фіксованих списків, значення обмежено 200 символами; правила, що звертаються до бази даних чи мережі або приймають регулярний вираз, не пропонуються. Класи: yf_validate, yf_form2.

Набори: E-mail Username Age Date IPv6 Card Name (any script)

Скинути
validate() повертає true.

Значення після підготовки: '4111 1111 1111 1111' (символів: 19)

ПравилоРезультатПовідомлення
trimготує
requiredпройдено
credit_cardпройдено

PHP

$rules = 'trim|required|credit_card';

// one value
$ok = validate(['value' => $value], ['value' => $rules]);

// a form2 field, errors are shown on it
echo form($_POST)
    ->validate(['value' => $rules])
    ->text('value')
    ->submit();

Правила

Вони виконуються в цьому порядку, згори донизу; наведіть на правило, щоб побачити, що воно приймає.

Підготовка
Наявність і довжина
Символи
Числа
Формати
Дати