validate() form()
Server-side validation of the posted form: rules per field, errors shown on the fields, the cleaned values for saving.
form()->validate($validate_rules = [], $post = [], $extra = [])Options
| Option | Meaning |
|---|---|
$validate_rules | Field => rules: a string trim|required|min_length[2], an array of rule names and callables ($value, $param, $data, &$error_msg); __form_id__ names the form when a page has several. |
$post | Data to check; default $_POST. |
on_before_validate, on_validate_ok, on_validate_error, on_after_validate | Callbacks, the same as the events. |
validate (field option) | Rules of one field in its options: text('email', ['validate' => 'required|valid_email']). |
Example
Code
$result = '';
$html = (string) form((array) $_POST, ['novalidate' => 1])
->validate([
'__form_id__' => 'docs_ref_validate',
'name' => 'trim|required|min_length[2]',
'email' => 'trim|required|valid_email',
'age' => ['trim', 'integer', fn ($in, $p, $d, &$msg) => ($in === '' || $in >= 13) || ! ($msg = 'Age: 13 or more')],
])
->on_validate_ok(function ($data) use (&$result) {
$result = '<div class="alert alert-success">Valid: ' . _prepare_html($data['name']) . ' <' . _prepare_html($data['email']) . '>. Nothing is stored.</div>';
})
->text('name')
->email()
->number('age')
->submit(['value' => 'Check']);
return $result . $html;Notes
- Rules are those of
yf_validate(see the validation rules demo);requiredandcaptchaalso add the HTMLrequiredattribute, sonovalidatelets the server answer in the demo. - Validation runs on a POST of this form only (its
__form_id__and CSRF token). - The valid values (
trimapplied) are what db_insert_if_ok() writes.
Bootstrap 3 and 5
Errors: has-error on the row and a help block under Bootstrap 3; is-invalid on the control and invalid-feedback under 5.
See also: form/events, form/db_insert_if_ok, demo:form/validate, demo:validate/rules