Validation

FormDataProcessor processes the data that comes with a form: it casts, sanitizes, transforms and validates the value of each field, and gives back the processed data and the errors. The rules are the ones of derafu/data-processor. Nobody writes them for the common cases: they are derived from the schema of the form, and the rules section of the definition adds the rest.

$result = $processor->process($form, $_POST);

if ($result->hasErrors()) {
    $errors = $result->getErrors();     // ['field' => ['message']]
    $form = $result->getForm();         // The form with its errors, to render it again.
} else {
    $data = $result->getProcessedData();
}

Typed Data Readers

ProcessResultInterface::getReader() returns a Derafu\Array\ArrayReader over the processed data. getProcessedData() continues to return the original value as mixed; requesting a reader requires that value to be an array, without converting its contents.

$result = $processor->process($form, ['contact' => ['address' => 'Street 1']]);
$reader = $result->getReader();

$address = $reader->requireString('contact.address');
$zone = $reader->getString('contact.zone', 'North');

The reader is also available on FormDataInterface. It is a snapshot: obtain another reader after changing FormData. Objects stored inside the array retain their identity.

use Derafu\Form\Data\FormData;

$data = new FormData(['contact' => ['address' => 'Street 1']]);
$before = $data->getReader();
$data->set('contact.address', 'Street 2');

$before->requireString('contact.address');           // 'Street 1'
$data->getReader()->requireString('contact.address'); // 'Street 2'

Reader keys use literal-key precedence and dot notation, including numeric positions. JSON Forms scopes such as #/properties/contact/properties/address belong to FormData’s existing get(), has() and set() methods; use contact.address with the reader.

Strict getters preserve existing types; explicit conversions use getAsXXX() / requireAsXXX(). Missing or null values return an optional getter’s default and fail a required read. The reader does not run form processing rules or change the processing result’s validity or errors. See Array Readers and Value Types.

Where the rules come from

For each field the processor joins three sources, in this order:

  1. The property of the schema: its type, format, pattern, limits, enum, etc. (see below).
  2. The control of the UI schema: a control of type file or image validates a file or an image (see Files), a control of type editor removes the tags of the HTML, and a control of type ipv4, ipv6, hostname, uuid, url, time, color, month or week validates that format.
  3. The rules section of the definition: explicit rules by field.
'rules' => [
    'name' => [
        'transform' => ['uppercase'],
        'validate' => ['min_length:3'],
    ],
],

The rules of a field are written in four categories, and are applied in this order: cast, transform, sanitize, validate. The explicit ones are joined to the derived ones like this:

  • cast: the explicit one replaces the derived one. When the type of the cast changes, the derived sanitizers (for example trim, that is for strings) are dropped, and the explicit ones are kept.
  • sanitize, transform and validate: the explicit ones are added after the derived ones.
  • required: the fields that are required (see Required fields) have it as the first rule of validate, once.

A field whose rule of the UI schema is not active (it is hidden, for example) is not validated and is not in the processed data, even if it came with the data.

Objects

The properties of an object of the schema are fields of the form with the name of their path, address.city, and the data has them inside the object, as PHP reads a form (address[city] in the name of the control):

'schema' => [
    'type' => 'object',
    'required' => ['contact'],
    'properties' => [
        'contact' => [
            'type' => 'object',
            'required' => ['address', 'zone'],
            'properties' => [
                'address' => ['type' => 'string'],
                'zone' => ['type' => 'string'],
                'city' => ['type' => 'string'],
            ],
        ],
    ],
],
'uischema' => [
    'type' => 'VerticalLayout',
    'elements' => [
        ['type' => 'Control', 'scope' => '#/properties/contact/properties/address'],
        ['type' => 'Control', 'scope' => '#/properties/contact/properties/zone'],
        ['type' => 'Control', 'scope' => '#/properties/contact/properties/city'],
    ],
],
$result = $processor->process($form, ['contact' => ['address' => 'Street 1', 'zone' => 'North', 'city' => '']]);

$result->getProcessedData();  // ['contact' => ['address' => 'Street 1', 'zone' => 'North', 'city' => '']]
$result->getErrors();         // ['contact.zone' => [...]] when the zone is missing.
  • The processed data and the data that comes back to the form have the same shape as the data that came.
  • The errors have the name of the path of the field (contact.zone).
  • A field is required by the required of its own object: address and zone are, city is not. The required of the root only asks for the key contact: it does not make any of its fields required.
  • A key with the whole name ('contact.address') is the value of that field too.
  • The conditions of the rules of the UI schema can be on a field of an object (#/properties/contact/properties/city).

Fields that are not in the schema

The form is closed: what comes with the data and is not a field of the form is not in the processed data. It is not an error, because a browser can send fields that are not of the form (the button that submitted it, for example). The additionalProperties of an object opens it:

additionalProperties of the object The fields of the data that are not in the form
absent, or false are dropped
true, or a schema are kept in the object as they came, without validating them

Each object decides for itself, the root included:

'schema' => [
    'type' => 'object',
    'properties' => [
        'name' => ['type' => 'string'],
        'contact' => [
            'type' => 'object',
            'additionalProperties' => true,
            'properties' => ['address' => ['type' => 'string']],
        ],
    ],
],
$result = $processor->process($form, ['name' => 'Ana', 'extra' => 'x', 'contact' => ['address' => 'Street 1', 'zip' => '123']]);

$result->getProcessedData();  // ['name' => 'Ana', 'contact' => ['address' => 'Street 1', 'zip' => '123']]

extra is dropped because the root is closed, and zip is kept because contact is open. The CSRF token and the response of the captcha are never in the processed data, and neither is a field that is not active.

Fields that depend on another

dependentRequired makes some fields of an object required when another one has a value:

'contact' => [
    'type' => 'object',
    'dependentRequired' => ['card' => ['address', 'zip']],
    'properties' => [
        'card' => ['type' => 'string'],
        'address' => ['type' => 'string'],
        'zip' => ['type' => 'string'],
    ],
],
$result = $processor->process($form, ['contact' => ['card' => '4111', 'address' => '', 'zip' => '']]);

$result->getErrors();  // ['contact.address' => ['Field is required.'], 'contact.zip' => ['Field is required.']]
  • A field has a value when it is not null, '' or [], as required reads it. The exception is the field that triggers: a checkbox that is not checked (false) is not a value, so “if it asks for an invoice, the tax id is required” does not ask for it when the box is empty.
  • The error is the one of required, in the path of each field that is missing.
  • The names are the ones of the object: in contact, card is contact.card. A name that is not a field of the form, or a field that is not active, is not required and does not trigger.

minProperties and maxProperties are not derived: the properties of an object are the fields of the schema, so their number does not depend on what the visitor sends.

What the schema validates

In the schema Rule
type: string cast string; sanitize trim
type: integer cast integer; validate int
type: number cast float; validate numeric
type: boolean cast boolean
minLength, maxLength min_length, max_length
minimum, maximum (integer and number) gte, lte
exclusiveMinimum, exclusiveMaximum, multipleOf (integer and number) gt, lt, multiple_of
minItems, maxItems, uniqueItems min_items, max_items, unique
contains, minContains, maxContains contains, min_contains, max_contains (see Arrays)
pattern regex (see below)
enum, const, or oneOf with const in with the values
items with enum or oneOf (a multiple selection) in with the values: each element must be one of them
contentMediaType: application/json json
format see the table below

A string is trimmed, except the one of a control of type password or with format: password: the spaces at its ends are part of it. A string with format: email is also transformed to lowercase.

The values of in are compared as text, and a comma that is in a value is escaped (\,) so it does not split it.

Formats

format Rule
email email
uri, url url
date date_format:Y-m-d
date-time datetime_local: YYYY-MM-DDTHH:MM[:SS], as <input type="datetime-local"> sends it
time time: HH:MM[:SS]
color color: #rrggbb
month month: YYYY-MM
week week: YYYY-Www
tel regex of telephone numbers
hostname hostname
ipv4, ipv6 ip:v4, ip:v6
uuid uuid
base64 base64
json json
regex regex_pattern: the value must be a regular expression
another no rule: it only changes the control that is drawn

Patterns

The pattern of JSON Schema is written without delimiters, like the browsers read the pattern attribute of HTML. PHP needs them, so the form gives the pattern the slash as its delimiter and escapes the slashes that it has, once: ^a/b$ and ^a\/b$ are the same pattern. The same conversion is used by the patterns of the types and by the conditions of the rules of the UI schema.

The regular expression is a PCRE one, the dialect of PHP. A pattern that can not be compiled is an error of the definition, not of the value: it is reported when the field is processed. A field with format: regex is the opposite: the value is the pattern, and it is invalid if it can not be compiled.

Booleans

For JSON Schema, required says that the key must be in the data, not that it has a given value. A boolean that is only required is valid when it is checked and when it is not. To ask for a value, fix it in the schema:

'terms' => [
    'type' => 'boolean',
    'title' => 'I accept the terms',
    'const' => true,          // or 'enum' => [true]
],
  • const: true or enum: [true] validate with accepted: the value must be true.
  • const: false or enum: [false] validate with declined: the value must be false.

A browser does not send a checkbox that is not checked, so a missing key is read as false, and the form that asks for true fails. The control has the native required too, see Required fields.

Arrays

contains is derived only when its schema is a const or an enum, because the rules compare the elements with a list of values:

In the schema Rule
contains: {const: 'terms'} contains:terms
contains: {enum: ['a', 'b']} contains:a,b
contains and minContains: 2 min_contains:2,a,b
contains and minContains: 0 no rule for the minimum
contains and maxContains: 3 max_contains:3,a,b

Without minContains, at least one element must be one of the values. The elements are compared as text, as in does. minContains and maxContains without contains are ignored, and so is a contains with another schema, or with values that the rules never match (a boolean, null, an array, an empty text).

Files

A control of type file or image has only the rules of the file: its value is an upload, so it is not cast or sanitized. The options of the control are:

  • max_size and min_size: a number of bytes, or a size with a unit (2M, 1.5Mi).
  • accept: the extensions (.pdf) and the types (application/pdf, image/*) that are accepted. The file is checked by its content, not by its name or by what the browser says. The types of an explicit mimetype rule are joined with the ones of accept.

Read-only fields

A property with readOnly: true is not taken from what came with the data. Its value is the one that the form has, the same that was drawn: the data of the form or, if it has none, the default of the schema, and null if there is neither. No rule is applied to it, so a required read-only field without a value is not an error.

// The form has the data ['code' => 'A-1'], and `code` is read-only.
$result = $processor->process($form, ['code' => 'HACK']);

$result->getProcessedData();  // ['code' => 'A-1']

The rules of the UI schema that depend on the field read the value of the form too, so what the visitor sends can not change them.

Translated errors

The messages of the errors are translated when the processor has a translator, see Translations.

On this page

Last updated on 09/11/2026 by Anonymous