diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e924f5..a5b0479 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ ## 2.0.0 [2026.06.10] A breaking release focused on correctness, safety and developer experience. -See [docs/upgrading-from-1.x.md](./docs/upgrading-from-1.x.md) for migration +See [docs/Migration-from-1.x.md](./docs/Migration-from-1.x.md) for migration notes. ### Breaking @@ -65,7 +65,7 @@ notes. optional lifecycle, callables, `extend()` and the fixed edge cases. - GitHub Actions CI (PHP 8.1–8.4, lowest/highest deps, style, static analysis, coverage) and `composer` scripts (`test`, `stan`, `cs-check`, `cs-fix`, `ci`). -- Documentation under [`docs/`](./docs/README.md). +- Documentation under [`docs/`](./docs/Home.md). ### 1.0.2 [2022.07.05] diff --git a/README.md b/README.md index 79ddcd7..0bb8bc6 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ or custom named rules, and get back localized error messages. [![CI](https://github.com/InitPHP/Validation/actions/workflows/ci.yml/badge.svg)](https://github.com/InitPHP/Validation/actions/workflows/ci.yml) [![Latest Stable Version](http://poser.pugx.org/initphp/validation/v)](https://packagist.org/packages/initphp/validation) [![Total Downloads](http://poser.pugx.org/initphp/validation/downloads)](https://packagist.org/packages/initphp/validation) [![License](http://poser.pugx.org/initphp/validation/license)](https://packagist.org/packages/initphp/validation) [![PHP Version Require](http://poser.pugx.org/initphp/validation/require/php)](https://packagist.org/packages/initphp/validation) -- [Documentation](./docs/README.md) +- [Documentation](./docs/Home.md) - [Changelog](./CHANGELOG.md) ## Requirements @@ -111,7 +111,7 @@ equivalent. Rule names are matched case-insensitively. | `strictOnly(a, b, ...)` | Case-sensitively equals one of the options. | | `creditCard(type?)` | A credit card number. Optional type: `amex`, `visa`, `mastercard`, `maestro`, `jcb`, `solo`, `switch`. | -See [`docs/rules-reference.md`](./docs/rules-reference.md) for a per-rule +See [`docs/Rules-Reference.md`](./docs/Rules-Reference.md) for a per-rule reference with examples. ## Callable rules @@ -198,7 +198,7 @@ $validation->setLocaleArray(['integer' => '{field} is not a whole number.']); ``` Point at your own language directory with `setLocaleDir()`. See -[`docs/localization-and-messages.md`](./docs/localization-and-messages.md). +[`docs/Localization.md`](./docs/Localization.md). ## Exceptions @@ -225,7 +225,7 @@ Version 2.0 is a breaking release. The headline changes: resolves in English, and several edge cases were fixed (argument trimming, open-ended `length`/`range` bounds, null-safety, loose `equals`/`again`). -Full notes: [`docs/upgrading-from-1.x.md`](./docs/upgrading-from-1.x.md). +Full notes: [`docs/Migration-from-1.x.md`](./docs/Migration-from-1.x.md). ## Testing diff --git a/docs/API-Reference.md b/docs/API-Reference.md new file mode 100644 index 0000000..e345c53 --- /dev/null +++ b/docs/API-Reference.md @@ -0,0 +1,213 @@ +# API Reference + +Everything lives on `InitPHP\Validation\Validation`. Every setter returns +`$this` for chaining unless noted otherwise. + +```php +use InitPHP\Validation\Validation; +``` + +## Contents + +- [Data](#data): [`__construct`](#__construct) · [`setData`](#setdata) · [`mergeData`](#mergedata) · [`getData`](#getdata) +- [Rules](#rules): [`rule`](#rule) · [`extend`](#extend) · [`pattern`](#pattern) +- [Running](#running): [`validation`](#validation) · [`isValid`](#isvalid) · [`clear`](#clear) +- [Errors](#errors): [`getError`](#geterror) · [`setError`](#seterror) +- [Localization](#localization): [`setLocale`](#setlocale) · [`setLocaleDir`](#setlocaledir) · [`setLocaleArray`](#setlocalearray) · [`labels`](#labels) +- [Misc](#misc): [`version`](#version) · [`VERSION`](#version-constant) + +--- + +## Data + +### `__construct` + +```php +public function __construct(array $data = []) +``` + +Create a validator with an optional initial data set. + +### `setData` + +```php +public function setData(array $data = []): self +``` + +Replace the entire data set. + +### `mergeData` + +```php +public function mergeData(array $data = []): self +``` + +Merge values into the current data set. Existing keys are overwritten. + +### `getData` + +```php +public function getData(): array +``` + +Return the current data set. + +--- + +## Rules + +### `rule` + +```php +public function rule(string|array $key, string|callable|array $rule, ?string $err = null): self +``` + +Queue one or more rules for one or more fields. + +- `$key` — a field name, a pipe-separated list (`"a|b"`), or an array of names. +- `$rule` — a pipe-separated DSL string, a callable, or an array mixing both. + The pseudo-rule `optional` marks the field(s) as allowed to be absent. +- `$err` — an optional custom message template for these rules. + +Throws [`InvalidArgumentException`](Exceptions.md#invalidargumentexception) if a key +or rule entry has an unsupported type. + +### `extend` + +```php +public function extend(string $name, callable $callback, ?string $message = null): self +``` + +Register a custom named rule usable from the DSL string. The callback receives +the value followed by any rule arguments and returns a boolean. Registered rules +persist across runs. See [Callable & Custom Rules](Callable-and-Custom-Rules.md). + +### `pattern` + +```php +public function pattern(string $name, string $pattern = '[\w]+'): self +``` + +Register or override a named pattern for the [`regex`](Rules-Reference.md#regex) +rule. Names are case-insensitive; the body has no delimiters and is matched as +`^(...)$`. See [Patterns & Regex](Patterns-and-Regex.md). + +--- + +## Running + +### `validation` + +```php +public function validation(): bool +``` + +Evaluate every queued rule. Clears the error list, runs each rule (skipping +[optional](Optional-Fields.md) absent fields), then empties the rule and optional +queues. Returns `true` when nothing failed. + +Throws [`UndefinedRuleException`](Exceptions.md#undefinedruleexception) if a string +rule names a rule that is neither built-in nor registered with `extend()`. + +### `isValid` + +```php +public function isValid(): bool +``` + +Return whether the most recent `validation()` run had no errors, without +re-running. + +### `clear` + +```php +public function clear(): self +``` + +Drop queued rules, optional flags and errors. Registered rules, patterns and the +loaded locale are kept. + +--- + +## Errors + +### `getError` + +```php +public function getError(): array +``` + +Return the list of messages from the most recent `validation()` run. + +### `setError` + +```php +public function setError(string $error, array $context = []): self +``` + +Append an interpolated message to the current error list. Note `validation()` +resets the list at the start of each run. + +--- + +## Localization + +### `setLocale` + +```php +public function setLocale(string $locale = 'en'): self +``` + +Load `.php` from the locale directory and merge it over the active +messages. Throws [`LocaleException`](Exceptions.md#localeexception) if the file is +missing or does not return an array. + +### `setLocaleDir` + +```php +public function setLocaleDir(string $dir = __DIR__ . '/languages/'): self +``` + +Set the directory language files are loaded from. Throws +[`LocaleException`](Exceptions.md#localeexception) if the directory does not exist. + +### `setLocaleArray` + +```php +public function setLocaleArray(array $assoc): self +``` + +Merge a partial set of message templates over the active locale. + +### `labels` + +```php +public function labels(array $assoc): self +``` + +Register display labels that replace raw field names in messages. + +--- + +## Misc + +### `version` + +```php +public function version(): string +``` + +Return the library version. + +### `VERSION` constant + +```php +public const VERSION = '2.0.0'; +``` + +The library version as a constant. + +## Next + +- [Exceptions](Exceptions.md) — the types thrown above. +- [Rules Reference](Rules-Reference.md) — what goes inside `rule()`. diff --git a/docs/Callable-and-Custom-Rules.md b/docs/Callable-and-Custom-Rules.md new file mode 100644 index 0000000..d74f006 --- /dev/null +++ b/docs/Callable-and-Custom-Rules.md @@ -0,0 +1,126 @@ +# Callable & Custom Rules + +When the [built-in rules](Rules-Reference.md) are not enough, there are three ways +to add your own logic: callback rules, mixed rule arrays, and registered named +rules. + +## Callback rules + +Pass a callable as the rule. It receives the field value and returns a boolean. +The third argument to `rule()` is the message used when it returns `false`. + +```php +use InitPHP\Validation\Validation; + +$v = new Validation(['number' => 13]); + +$v->rule('number', static function ($value): bool { + return ($value % 2) === 0; +}, '{field} must be an even number.'); + +$v->validation(); // false +$v->getError(); // ["number must be an even number."] +``` + +The callback is always called with the field value, or `null` when the field is +absent. Without a custom message a failed callback uses the generic message +("The {field} value is not valid."). + +```php +// the value is null here because 'missing' has no data +$v->rule('missing', static function ($value): bool { + return $value !== null; +}); +``` + +## Mixed rule arrays + +A rule can be an array that mixes DSL strings and callbacks. They run in order, +left to right. + +```php +$v->rule('quantity', [ + 'required', + 'integer', + static fn ($value): bool => $value > 0, +]); +``` + +## Named rules with `extend()` + +Callbacks are per-field. To reuse a rule across fields — and call it from a DSL +string **with arguments** — register it with `extend()`: + +```php +$v->extend( + 'divisible', + static fn ($value, $by): bool => ((int) $value % (int) $by) === 0, + '{field} must be divisible by {2}.' +); + +$v->rule('quantity', 'divisible(5)'); +$v->rule('weight', 'divisible(10)'); +``` + +`extend(string $name, callable $callback, ?string $message = null)`: + +- `$name` is matched **case-insensitively**, like the built-in rules. +- `$callback` receives the value followed by any DSL arguments (always strings) + and returns a boolean. +- `$message` is optional; when given it becomes the template for that rule and + can use `{field}` and [positional placeholders](Error-Messages.md). + +### Registered rules persist + +A registered rule survives `validation()` runs and is **not** cleared by +`clear()`, so register it once during setup: + +```php +$v->extend('even', static fn ($value): bool => ((int) $value % 2) === 0); + +$v->setData(['a' => 4])->rule('a', 'even')->validation(); // true +$v->setData(['a' => 5])->rule('a', 'even')->validation(); // false +``` + +### Overriding a built-in rule + +A registered rule with the same name as a built-in **overrides** it — useful for +swapping in a stricter check: + +```php +$v->extend('mail', static function ($value): bool { + return is_string($value) + && filter_var($value, FILTER_VALIDATE_EMAIL) + && str_ends_with($value, '@example.com'); +}); +``` + +## Which one to use? + +| Need | Use | +| --- | --- | +| One-off check for a single field | Callback rule | +| Several checks, some custom, on one field | Mixed rule array | +| A reusable rule shared across fields, usable in the DSL string | `extend()` | + +## A worked example: a domain rule + +```php +use InitPHP\Validation\Validation; + +$v = new Validation(['website' => 'https://example.org']); + +$v->extend( + 'httpsUrl', + static fn ($value): bool => is_string($value) && str_starts_with($value, 'https://'), + '{field} must use HTTPS.' +); + +$valid = $v->rule('website', 'required|url|httpsUrl')->validation(); +``` + +## Next + +- [Error Messages](Error-Messages.md) — message templates and placeholders. +- [Patterns & Regex](Patterns-and-Regex.md) — reusable regex via `pattern()`. +- [API Reference](API-Reference.md) — `extend()` and the rest of the surface. diff --git a/docs/Error-Messages.md b/docs/Error-Messages.md new file mode 100644 index 0000000..4de7950 --- /dev/null +++ b/docs/Error-Messages.md @@ -0,0 +1,121 @@ +# Error Messages + +When a rule fails, the validator builds a message from a template and adds it to +the error list. This page covers placeholders, custom messages and labels. +Switching language is covered in [Localization](Localization.md). + +## Reading errors + +```php +use InitPHP\Validation\Validation; + +$v = new Validation(['age' => 5]); +$v->rule('age', 'min(18)'); +$v->validation(); + +$v->getError(); // ["age must be greater than or equal to 18."] +``` + +`getError()` returns a **flat list** of message strings from the most recent +`validation()` run. The field name is embedded in each message (see +[per-field errors](#getting-errors-per-field) below). + +## Placeholders + +Templates support `{field}` and positional placeholders: + +| Placeholder | Value | +| --- | --- | +| `{field}` / `{0}` | The field name (passed through [labels](#labels)). | +| `{1}` | The field value being validated. | +| `{2}` | The first rule argument. | +| `{3}`, `{4}`, ... | The second, third, ... rule arguments. | + +```php +$v->rule('age', 'min(18)'); +// template: "{field} must be greater than or equal to {2}." +// result: "age must be greater than or equal to 18." ({2} = 18) +``` + +## Per-rule custom messages + +The third argument to `rule()` overrides the message for that call, with the +same placeholders available: + +```php +$v->rule('age', 'min(18)', '{field} is too young (min {2}).'); +// "age is too young (min 18)." +``` + +This works for callback rules too: + +```php +$v->rule('number', static fn ($value): bool => ((int) $value % 2) === 0, + '{field} must be even.'); +``` + +## Labels + +`labels()` maps raw field names to friendly display names. Only `{field}` is +passed through labels — **rule arguments are never label-substituted**, so a +value that happens to match a label is left untouched. + +```php +$v->labels(['age' => 'Age', 'email' => 'E-mail address']); +$v->rule('age', 'min(18)'); +// "Age must be greater than or equal to 18." +``` + +## Several errors + +Every failed rule adds its own message, so one run can return many: + +```php +$v = new Validation(['a' => 'x', 'b' => 'y']); +$v->rule('a', 'integer'); +$v->rule('b', 'integer'); +$v->validation(); +$v->getError(); // 2 messages +``` + +## Getting errors per field + +`getError()` is a flat list. When you need messages grouped by field, validate +each field in its own run and collect the results — remember that `validation()` +consumes the queue each time: + +```php +$rules = [ + 'username' => 'required|alphanum|length(3...20)', + 'email' => 'required|mail', + 'age' => 'optional|integer|range(18...120)', +]; + +$errors = []; +foreach ($rules as $field => $rule) { + $v->rule($field, $rule); + if (!$v->validation()) { + $errors[$field] = $v->getError(); + } +} +// $errors['email'] => ["email must be an e-mail address."] +``` + +Alternatively, write each message with a custom template so it is +self-describing in a flat list. + +## Adding a message manually + +`setError()` appends an interpolated message to the current list: + +```php +$v->setError('{field} could not be processed.', ['field' => 'avatar']); +``` + +Note that `validation()` clears the error list at the **start** of each run, so +add manual errors *after* validating. + +## Next + +- [Localization](Localization.md) — translate messages or ship your own language. +- [Rules Reference](Rules-Reference.md) — every built-in rule and its arguments. diff --git a/docs/Exceptions.md b/docs/Exceptions.md new file mode 100644 index 0000000..5008054 --- /dev/null +++ b/docs/Exceptions.md @@ -0,0 +1,85 @@ +# Exceptions + +Every exception the package throws lives under `InitPHP\Validation\Exception` and +implements the marker interface `ExceptionInterface`, so you can catch them all +at once. + +``` +Throwable +└── ExceptionInterface (interface) + ├── ValidationException (extends \RuntimeException) + │ ├── UndefinedRuleException + │ └── LocaleException + └── InvalidArgumentException (extends \InvalidArgumentException) +``` + +> A **failed validation is not an exception** — it is the normal `false` return +> of `validation()`, with messages in `getError()`. Exceptions are reserved for +> configuration and programming errors. + +## UndefinedRuleException + +Thrown by `validation()` when a string rule names a rule that is neither built-in +nor registered with [`extend()`](Callable-and-Custom-Rules.md). Unknown rules fail +loudly rather than silently passing — a misspelled rule is a bug, not a valid +field. + +```php +use InitPHP\Validation\Exception\UndefinedRuleException; + +$v->rule('age', 'integerr'); // typo +try { + $v->validation(); +} catch (UndefinedRuleException $e) { + echo $e->getMessage(); // 'The validation rule "integerr" is not defined.' +} +``` + +## InvalidArgumentException + +Thrown by `rule()` when a key or rule entry has an unsupported type — for example +an array rule entry that is neither a string nor a callable. It extends the SPL +`\InvalidArgumentException` and also implements `ExceptionInterface`. + +```php +use InitPHP\Validation\Exception\InvalidArgumentException; + +try { + $v->rule('age', [123]); // 123 is not a string or callable +} catch (InvalidArgumentException $e) { + // ... +} +``` + +## LocaleException + +Thrown by `setLocale()` and `setLocaleDir()` when a locale cannot be loaded: the +directory does not exist, the file is missing, or the file does not return an +array. + +```php +use InitPHP\Validation\Exception\LocaleException; + +try { + $v->setLocale('xx'); +} catch (LocaleException $e) { + // could not find the language file +} +``` + +## Catching everything + +```php +use InitPHP\Validation\Exception\ExceptionInterface; + +try { + $v->rule('age', 'integer')->validation(); +} catch (ExceptionInterface $e) { + // any failure originating from InitPHP Validation +} +``` + +## Next + +- [API Reference](API-Reference.md) — which method throws what. +- [Troubleshooting](Troubleshooting.md) — common causes and fixes. diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..e33d7cd --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,76 @@ +# FAQ + +### Does a failed validation throw an exception? + +No. A failed validation is the normal `false` return of `validation()`, with the +messages available from `getError()`. Exceptions are reserved for programming and +configuration errors — see [Exceptions](Exceptions.md). + +### Why did my rule throw `UndefinedRuleException`? + +The rule name is not a built-in rule or a rule registered with `extend()` — +usually a typo (`integerr`, `requierd`). Unknown rules fail loudly so a typo +never silently skips validation. See +[Migration from 1.x](Migration-from-1.x.md#unknown-rules-now-throw). + +### Why doesn't my second `validation()` re-check earlier rules? + +`validation()` **consumes** the rule queue. Each run validates only the rules +queued since the last run. Queue rules again if you need them re-checked — see +[The Validation Lifecycle](The-Validation-Lifecycle.md). + +### How do I get errors grouped by field? + +`getError()` returns a flat list. Validate each field in its own run and key the +results, or use self-describing custom messages. See +[Error Messages](Error-Messages.md#getting-errors-per-field) and the +[Recipes](Recipes.md#errors-grouped-by-field). + +### My `optional` field still fails — why? + +`optional` only skips a field that is **missing or `null`**. An empty string +(`''`) counts as present, so its rules still run. See +[Optional Fields](Optional-Fields.md#when-is-a-field-absent). + +### How do I add a rule the library doesn't have? + +Three ways: a [callback rule](Callable-and-Custom-Rules.md#callback-rules) for a +one-off check, a [mixed rule array](Callable-and-Custom-Rules.md#mixed-rule-arrays), +or [`extend()`](Callable-and-Custom-Rules.md#named-rules-with-extend) for a reusable +named rule. + +### Can I validate arrays / nested data? + +The value of a field can be an array — rules like +[`array`](Rules-Reference.md#array), [`in`](Rules-Reference.md#in), +[`min`](Rules-Reference.md#min) (element count) and +[`startWith`](Rules-Reference.md#startwith) understand arrays. For deeply nested +structures, validate each sub-array with its own `setData()` / +`validation()` cycle (see [Recipes → Validate a list](Recipes.md#validate-a-list-of-items)). + +### Can I reuse one validator instance? + +Yes — and you should. Configure the locale, labels, patterns and custom rules +once; they survive every run. Only the rule queue and errors reset. See +[Recipes](Recipes.md#a-reusable-pre-configured-validator). + +### Which languages ship with the package? + +English (`en`, default) and Turkish (`tr`). You can override messages or load +your own language directory — see [Localization](Localization.md). + +### Which PHP versions are supported? + +PHP 8.2 and newer, with `ext-mbstring`. CI runs 8.2, 8.3, 8.4 and 8.5. Older +runtimes need an earlier release: 2.0.0 supports PHP 8.1, and the 1.x line +supports PHP 7.4. + +### Is this a PSR validation implementation? + +No — there is no PSR for validation. The package is standalone and +dependency-free. + +## Next + +- [Troubleshooting](Troubleshooting.md) — concrete problems and fixes. +- [Rules Reference](Rules-Reference.md) — the full rule catalogue. diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000..5608f79 --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,97 @@ +# InitPHP Validation — Wiki + +Welcome to the official documentation for **`initphp/validation`** — a fast, +dependency-free data-validation library for **PHP 8.2+**. + +You describe what each field should look like with a small rule DSL, callbacks, +or your own named rules, and get back localized error messages. + +```bash +composer require initphp/validation +``` + +```php +use InitPHP\Validation\Validation; + +$validation = new Validation([ + 'name' => 'Muhammet', + 'year' => '2022', +]); + +$valid = $validation + ->rule('name', 'required|string') + ->rule('year', 'integer|range(1970...2099)') + ->validation(); + +if (!$valid) { + foreach ($validation->getError() as $message) { + echo $message, "\n"; + } +} +``` + +## The package in one table + +| Symbol | Role | +| --- | --- | +| [`Validation`](API-Reference.md) | The single entry point: holds the data, the rule queue, the errors and the active locale. | +| [`extend()`](Callable-and-Custom-Rules.md#named-rules-with-extend) | Register a reusable named rule usable from the DSL string. | +| [`ExceptionInterface`](Exceptions.md) | Marker implemented by every exception the package throws. | +| [`UndefinedRuleException`](Exceptions.md#undefinedruleexception) | Thrown when a rule name is unknown — unknown rules fail loudly, they never silently pass. | + +## Start here + +- **New to the package?** Read [Installation](Installation.md), then + [Quick Start](Quick-Start.md). +- **Want the mental model?** + [The Validation Lifecycle](The-Validation-Lifecycle.md) explains the + *queue → validate → read* loop. +- **Looking for a rule?** Every built-in rule is in the + [Rules Reference](Rules-Reference.md). +- **Need custom logic?** + [Callable & Custom Rules](Callable-and-Custom-Rules.md). +- **Localizing messages?** [Error Messages](Error-Messages.md) and + [Localization](Localization.md). +- **Coming from 1.x?** Read [Migration from 1.x](Migration-from-1.x.md) — 2.0 is a + breaking release. + +## What you get + +- **A readable rule DSL.** Pipe rules together per field: + `"required|integer|range(1...10)"`. Arguments go in parentheses and are + trimmed. See the [Rules Reference](Rules-Reference.md). +- **30+ built-in rules** for types, text, contact info, sizes, dates, patterns + and comparisons. +- **Callbacks and custom named rules.** Drop in a closure for a one-off check, + or register a reusable rule with [`extend()`](Callable-and-Custom-Rules.md). +- **Localized messages.** Ships with English and Turkish; placeholders, labels + and per-rule overrides are all supported. See [Localization](Localization.md). +- **Fails loud, not silent.** An unknown rule throws instead of quietly passing + a field. See [Exceptions](Exceptions.md). +- **Zero runtime dependencies** beyond `ext-mbstring`. + +## At a glance — a few rules + +| Rule | Passes | Fails | +| --- | --- | --- | +| `integer` | `"12"`, `-3` | `"3.5"`, `"abc"` | +| `mail` | `a@b.com` | `not-an-email` | +| `range(1970...2099)` | `2022` | `1900` | +| `length(3...20)` | `"hello"` | `"ab"` | +| `again(password)` | confirm equals `password` | they differ | +| `only(small, medium, large)` | `"Medium"` | `"xl"` | + +## Package metadata + +- **License**: MIT +- **Minimum PHP**: 8.2 +- **Required extensions**: `ext-mbstring` +- **Runtime dependencies**: none +- **Packagist**: [`initphp/validation`](https://packagist.org/packages/initphp/validation) +- **Source**: [github.com/InitPHP/Validation](https://github.com/InitPHP/Validation) +- **Issues**: [github.com/InitPHP/Validation/issues](https://github.com/InitPHP/Validation/issues) +- **Discussions**: [github.com/orgs/InitPHP/discussions](https://github.com/orgs/InitPHP/discussions) + +If something in this wiki is unclear, wrong, or out of date, +[open an issue](https://github.com/InitPHP/Validation/issues/new) — documentation +fixes are merged eagerly. diff --git a/docs/Installation.md b/docs/Installation.md new file mode 100644 index 0000000..749c3d8 --- /dev/null +++ b/docs/Installation.md @@ -0,0 +1,48 @@ +# Installation + +## Requirements + +- **PHP 8.2 or newer** +- **`ext-mbstring`** (used for Unicode-aware length and case handling) +- No runtime dependencies beyond the PHP core + +## Install with Composer + +```bash +composer require initphp/validation +``` + +Then make sure Composer's autoloader is loaded: + +```php +require __DIR__ . '/vendor/autoload.php'; +``` + +## Verify the install + +```php + 'abc']); +$v->setLocale('tr'); +$v->rule('age', 'integer'); +$v->validation(); +$v->getError(); // ["age bir tam sayı olmalıdır."] +``` + +The loaded locale persists across `validation()` runs, so call `setLocale()` +once during setup. + +## Overriding individual messages + +`setLocaleArray()` merges a partial set of templates over the active locale — +handy for tweaking a few messages without a whole file. + +```php +$v->setLocaleArray([ + 'integer' => '{field} must be a whole number.', + 'required' => 'Please fill in {field}.', +]); +``` + +Message keys are matched **case-insensitively** against rule names, so a key of +`creditCard` or `creditcard` both apply to the `creditCard` rule. Placeholders +work exactly as in [Error Messages](Error-Messages.md). + +## Using your own language directory + +`setLocaleDir()` points the loader at a directory of `.php` files; then +`setLocale()` loads from there. + +```php +$v->setLocaleDir(__DIR__ . '/lang'); +$v->setLocale('de'); // loads __DIR__/lang/de.php +``` + +A language file returns an associative array of templates: + +```php + '{field} darf nicht leer sein.', + 'integer' => '{field} muss eine Ganzzahl sein.', + 'mail' => '{field} muss eine E-Mail-Adresse sein.', + // ... one entry per rule you want to translate +]; +``` + +Any rule without a matching key falls back to the `notValidDefault` template +("The {field} value is not valid."). + +## The message keys + +Keys are rule names. The full set ships in +[`src/languages/en.php`](https://github.com/InitPHP/Validation/blob/main/src/languages/en.php): + +``` +notValidDefault, callable, integer, float, numeric, string, boolean, array, +mail, mailHost, url, urlHost, empty, required, min, max, length, range, regex, +date, dateFormat, ip, ipv4, ipv6, again, equals, startWith, endWith, in, notIn, +alpha, alphaNum, alphanumeric, creditCard, only, strictOnly, contains, notContains +``` + +The special `callable` key is used when a [callback rule](Callable-and-Custom-Rules.md) +fails without its own message; `notValidDefault` is the catch-all fallback. + +## Order matters + +`setLocale()` and `setLocaleArray()` **merge** over what is already active. +Apply the base language first, then your overrides: + +```php +$v->setLocale('tr'); // base language +$v->setLocaleArray(['mail' => '{field} hatalı.']); // then tweak +``` + +## Next + +- [Error Messages](Error-Messages.md) — placeholders, labels and custom messages. +- [API Reference](API-Reference.md) — the locale methods in full. diff --git a/docs/upgrading-from-1.x.md b/docs/Migration-from-1.x.md similarity index 50% rename from docs/upgrading-from-1.x.md rename to docs/Migration-from-1.x.md index a5a555f..a3c4bb1 100644 --- a/docs/upgrading-from-1.x.md +++ b/docs/Migration-from-1.x.md @@ -1,32 +1,33 @@ -# Upgrading from 1.x to 2.0 +# Migration from 1.x Version 2.0 is a breaking release that fixes long-standing bugs and tightens the API. Most existing rule strings keep working unchanged; the breaking changes are -about PHP version, error behaviour and a few corrected edge cases. +about the PHP version, error behaviour and a few corrected edge cases. ## Requirements -- **PHP 8.1 or newer** is now required (1.x supported 7.4+). +- **PHP 8.1 or newer** is required by 2.0.0 (1.x supported 7.4+). The current + `main` branch raises this to **PHP 8.2 or newer**. ## Behaviour changes you may need to act on ### Unknown rules now throw In 1.x a misspelled or unknown rule was silently ignored and the field counted -as valid. In 2.0 it throws `UndefinedRuleException`. +as valid. In 2.0 it throws [`UndefinedRuleException`](Exceptions.md#undefinedruleexception). ```php $v->rule('age', 'integerr'); // 1.x: silently passes — 2.0: throws ``` -Fix any typos, and register custom names with [`extend()`](custom-rules-and-callables.md). +Fix any typos, and register custom names with +[`extend()`](Callable-and-Custom-Rules.md). ### Rules are no longer dispatched to global functions In 1.x a rule name that matched a global function (e.g. `ctype_digit`) was -invoked with the field value. This was surprising and unsafe and has been -removed. Such names now throw `UndefinedRuleException`. Wrap the logic in a -callback or `extend()` instead: +invoked with the field value. This was surprising and unsafe, and has been +removed. Such names now throw. Wrap the logic in a callback or `extend()`: ```php $v->extend('ctype_digit', static fn ($value): bool => ctype_digit((string) $value)); @@ -38,51 +39,53 @@ Passing a callback as the rule used to throw a `TypeError`. It now works as documented: ```php -$v->rule('number', static fn ($value): bool => ($value % 2) === 0, '{field} must be even.'); +$v->rule('number', static fn ($value): bool => ((int) $value % 2) === 0, + '{field} must be even.'); ``` ### Error messages - The `again` rule now resolves its English message (it previously fell back to the generic "not valid" text). -- Message keys resolve case-insensitively, so writing `creditcard` or - `creditCard` produces the same message. +- Message keys resolve **case-insensitively**, so `creditcard` and `creditCard` + produce the same message. - The Turkish `notContains` message now reads "must not contain". -If you relied on the old (incorrect) message strings in tests, update those -expectations. +If your tests asserted the old (incorrect) strings, update those expectations. ### Corrected edge cases These were bugs; the new behaviour is what the documentation always implied: -- Arguments are trimmed, so `only(a, b, c)` matches the same way as `only(a,b,c)`. +- Arguments are trimmed, so `only(a, b, c)` matches like `only(a,b,c)`. - Open-ended `length` works: `length(...255)` now enforces the maximum. - `length` on a `null` value returns `false` instead of raising a warning. - `min`/`max` on arrays measure the element count without a type warning. - `equals` and `again` compare loosely, so `equals(123)` matches the integer `123`. +- The built-in `slug` regex pattern matches multiple characters (it was missing + its `+` quantifier). ## Exceptions -`setLocale()` / `setLocaleDir()` now throw `InitPHP\Validation\Exception\LocaleException` -(previously `\InvalidArgumentException` / `\Exception`), and `rule()` throws -`InitPHP\Validation\Exception\InvalidArgumentException`. All package exceptions -implement `InitPHP\Validation\Exception\ExceptionInterface`. If you catch the -SPL types, note that `InvalidArgumentException` still extends -`\InvalidArgumentException`; the locale errors now need the new type or the -marker interface. +`setLocale()` / `setLocaleDir()` now throw +[`LocaleException`](Exceptions.md#localeexception) (previously +`\InvalidArgumentException` / `\Exception`), and `rule()` throws +[`InvalidArgumentException`](Exceptions.md#invalidargumentexception). All package +exceptions implement `ExceptionInterface`. If you catch the SPL types, note that +`InvalidArgumentException` still extends `\InvalidArgumentException`; the locale +errors now need the new type or the marker interface. ## New in 2.0 -- [`extend()`](custom-rules-and-callables.md) for reusable custom named rules. -- [`getData()`](api-reference.md#getdata-array) accessor. +- [`extend()`](Callable-and-Custom-Rules.md) for reusable custom named rules. +- [`getData()`](API-Reference.md#getdata) accessor. - An `alphanumeric` alias for `alphanum`. - Typed signatures, full PHPDoc, PHPStan (max) and PSR-12 compliance. ## Quick checklist -1. Bump your PHP requirement to 8.1+. +1. Bump your PHP requirement to 8.1+ (8.2+ for the current `main` branch). 2. Search your rule strings for typos and any global-function names. 3. Update tests that asserted old message text. 4. Catch the new exception types where you load locales. diff --git a/docs/Optional-Fields.md b/docs/Optional-Fields.md new file mode 100644 index 0000000..0fba8f4 --- /dev/null +++ b/docs/Optional-Fields.md @@ -0,0 +1,83 @@ +# Optional Fields + +Not every field is required. The `optional` pseudo-rule lets a field be absent +without failing, while still validating it when it **is** present. + +## What `optional` does + +`optional` is not a check — it is a flag. When the field has no value, every +other rule queued for it is **skipped**. When the field is present, the other +rules apply as normal. + +```php +use InitPHP\Validation\Validation; + +// 'nickname' is missing entirely +$v = new Validation([]); +$v->rule('nickname', 'optional|alpha'); +$v->validation(); // true — skipped, nothing to check + +// 'nickname' is present but invalid +$v = new Validation(['nickname' => '123']); +$v->rule('nickname', 'optional|alpha'); +$v->validation(); // false — present, so 'alpha' runs and fails +``` + +## When is a field "absent"? + +A field counts as absent when its key is **missing** or its value is **`null`**. +An empty string (`''`) is considered **present**, so `optional` will not skip it: + +```php +$v = new Validation(['nickname' => '']); +$v->rule('nickname', 'optional|alpha'); +$v->validation(); // false — '' is present, and '' is not alphabetic +``` + +If you want to allow blanks too, combine `optional` with a rule that accepts +empty input, or branch on the value before queueing rules: + +```php +if (($data['nickname'] ?? '') !== '') { + $v->rule('nickname', 'alpha|length(2...20)'); +} +``` + +## `optional` and the lifecycle + +`optional` flags are reset at the end of each `validation()` run, exactly like +the rule queue. So an `optional` mark only applies to the run it was added in: + +```php +$v = new Validation([]); + +$v->rule('email', 'optional|required'); +$v->validation(); // true — email is optional this run + +$v->rule('email', 'required'); +$v->validation(); // false — the optional flag did not carry over +``` + +This keeps each *queue → validate* cycle independent. See +[The Validation Lifecycle](The-Validation-Lifecycle.md). + +## Marking several fields optional + +`optional` works with piped field names and across separate `rule()` calls: + +```php +$v->rule('phone|fax', 'optional'); +$v->rule('phone', 'tel'); // a named pattern, see Patterns & Regex +$v->rule('fax', 'tel'); +``` + +You can also place `optional` anywhere in the pipe; order does not matter for it: + +```php +$v->rule('middle_name', 'alpha|optional'); // same as 'optional|alpha' +``` + +## Next + +- [Rules Reference](Rules-Reference.md) — the rules you combine with `optional`. +- [The Validation Lifecycle](The-Validation-Lifecycle.md) — why flags reset each run. diff --git a/docs/Patterns-and-Regex.md b/docs/Patterns-and-Regex.md new file mode 100644 index 0000000..ac4b42c --- /dev/null +++ b/docs/Patterns-and-Regex.md @@ -0,0 +1,80 @@ +# Patterns & Regex + +The [`regex`](Rules-Reference.md#regex) rule matches a value against a regular +expression — either an inline body or the name of a pattern you registered. + +## Inline regex + +Pass the regex **body without delimiters**. The value is matched anchored as +`^(...)$`, so the whole value must match. + +```php +use InitPHP\Validation\Validation; + +$v = new Validation(['code' => 'AB12']); +$v->rule('code', 'regex([A-Z]{2}[0-9]{2})'); // passes +``` + +> **Commas are argument separators.** An inline body containing a comma — such as +> `[a-z]{2,4}` — is split before it reaches the regex engine. Register it as a +> named pattern instead (below). + +## Named patterns + +Give a pattern a name once and reference it by name. Names are matched +case-insensitively and persist across `validation()` runs. + +```php +$v->pattern('product_code', '[A-Z]{2}-[0-9]{4}'); +$v->rule('sku', 'regex(product_code)'); +``` + +`pattern(string $name, string $body)` adds or overrides a named pattern. The +body has no delimiters and is matched as `^(...)$`. + +## Built-in patterns + +These names are available to `regex` out of the box: + +| Name | Matches | +| --- | --- | +| `uri` | URI path characters | +| `slug` | URL slug characters (letters, digits, `-`, `_`) | +| `url` | URL characters | +| `alpha` | Unicode letters | +| `words` | Letters and whitespace | +| `alphanum` | Letters and digits | +| `int` | Digits | +| `float` | Digits, dot and comma | +| `tel` | Phone-number characters (`0-9 + space ( ) -`) | +| `text` | Common prose characters | +| `file` | A file name with an extension | +| `folder` | A folder name | +| `address` | Street-address characters | +| `date_dmy` | `d-m-Y` style dates | +| `date_ymd` | `Y-m-d` style dates | +| `email` | A basic e-mail shape | + +```php +$v->rule('handle', 'regex(slug)'); // "my-blog-post_2" passes +$v->rule('phone', 'regex(tel)'); +``` + +## `regex` vs the dedicated rules + +For common cases, prefer the purpose-built rule over a raw pattern — they are +clearer and handle edge cases (types, `filter_var`) for you: + +| Instead of | Prefer | +| --- | --- | +| `regex(email)` | [`mail`](Rules-Reference.md#mail) | +| `regex(int)` | [`integer`](Rules-Reference.md#integer) | +| `regex(alphanum)` | [`alphanum`](Rules-Reference.md#alphanum--alphanumeric) | + +Reach for `regex` when you need a shape the built-in rules do not express. + +## Next + +- [Rules Reference](Rules-Reference.md#regex) — the `regex` rule entry. +- [Callable & Custom Rules](Callable-and-Custom-Rules.md) — for logic regex cannot + express. diff --git a/docs/Quick-Start.md b/docs/Quick-Start.md new file mode 100644 index 0000000..60ecef2 --- /dev/null +++ b/docs/Quick-Start.md @@ -0,0 +1,116 @@ +# Quick Start + +From `composer require` to a validated form in a few minutes. + +## 1. Create the validator with your data + +Any associative array works — `$_POST`, `$_GET`, a decoded JSON body, or a +plain array. + +```php +setData(['email' => 'a@b.com']); +$validation->mergeData(['name' => 'Ada']); +``` + +## 2. Queue rules + +Each `rule()` call adds checks for a field. A rule string is a pipe-separated +list, evaluated left to right. `rule()` is chainable. + +```php +$validation + ->rule('name', 'required|string') + ->rule('email', 'required|mail') + ->rule('age', 'integer|range(18...120)'); +``` + +See the [Rules Reference](Rules-Reference.md) for every rule. + +## 3. Validate + +`validation()` runs the whole queue and returns a boolean. + +```php +if ($validation->validation()) { + // all good — use the data +} else { + // something failed +} +``` + +## 4. Read the errors + +`getError()` returns the messages from the most recent run. + +```php +foreach ($validation->getError() as $message) { + echo $message, "\n"; +} +// e.g. "age must be greater than or equal to 18." +``` + +`isValid()` returns the same boolean as the last `validation()` call without +re-running it. + +## A complete example + +```php + 'ada', + 'email' => 'ada@example.com', + 'password' => 'sup3rsecret', + 'confirm' => 'sup3rsecret', + 'age' => '34', +]); + +$valid = $validation + ->rule('username', 'required|alphanum|length(3...20)') + ->rule('email', 'required|mail') + ->rule('password', 'required|length(8...)') + ->rule('confirm', 'again(password)') + ->rule('age', 'optional|integer|range(18...120)') + ->validation(); + +if ($valid) { + // persist the user +} else { + $errors = $validation->getError(); +} +``` + +## Add a quick custom check + +Need something the built-in rules do not cover? Pass a callback as the rule and +give it a message: + +```php +$validation->rule('number', static function ($value): bool { + return ($value % 2) === 0; +}, '{field} must be an even number.'); +``` + +More in [Callable & Custom Rules](Callable-and-Custom-Rules.md). + +## Next + +- [The Validation Lifecycle](The-Validation-Lifecycle.md) — the mental model. +- [Rules Reference](Rules-Reference.md) — the full catalogue. +- [Recipes](Recipes.md) — copy-paste patterns for common forms. diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 04ca592..0000000 --- a/docs/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# InitPHP Validation — Documentation - -InitPHP Validation checks that an associative data set matches a list of rules. -Rules are written as a small DSL string (`"required|integer|range(1...10)"`), -callbacks, or custom named rules, and failures become localized messages. - -## Contents - -| Guide | What it covers | -| ----- | -------------- | -| [Getting started](getting-started.md) | Install, the `Validation` object, the queue → validate → read loop. | -| [Rules reference](rules-reference.md) | Every built-in rule, grouped, with signatures and examples. | -| [Custom rules & callables](custom-rules-and-callables.md) | Callback rules, mixed rule arrays and `extend()`. | -| [Optional fields & patterns](optional-and-patterns.md) | The `optional` pseudo-rule, the validation lifecycle and named regex patterns. | -| [Localization & messages](localization-and-messages.md) | Placeholders, labels, locales, custom messages and language files. | -| [API reference](api-reference.md) | Every public method, its signature and behaviour. | -| [Exceptions](exceptions.md) | What is thrown, when, and how to catch it. | -| [Upgrading from 1.x](upgrading-from-1.x.md) | Breaking changes in 2.0 and how to migrate. | - -## At a glance - -```php -require 'vendor/autoload.php'; - -use InitPHP\Validation\Validation; - -$validation = new Validation([ - 'name' => 'Muhammet', - 'year' => '2022', -]); - -$valid = $validation - ->rule('name', 'required|string') - ->rule('year', 'integer|range(1970...2099)') - ->validation(); - -if (!$valid) { - foreach ($validation->getError() as $message) { - echo $message, "\n"; - } -} -``` - -## Requirements - -- PHP 8.1 or newer -- `ext-mbstring` diff --git a/docs/Recipes.md b/docs/Recipes.md new file mode 100644 index 0000000..355bfe0 --- /dev/null +++ b/docs/Recipes.md @@ -0,0 +1,178 @@ +# Recipes + +Practical, copy-pasteable patterns built only from the public API. See the +[API Reference](API-Reference.md) and [Rules Reference](Rules-Reference.md). + +## Validate a registration form + +```php +use InitPHP\Validation\Validation; + +$v = new Validation($_POST); + +$valid = $v + ->rule('username', 'required|alphanum|length(3...20)') + ->rule('email', 'required|mail') + ->rule('password', 'required|length(8...)') + ->rule('confirm', 'again(password)') + ->rule('terms', 'equals(1)') + ->validation(); + +if (!$valid) { + $errors = $v->getError(); +} +``` + +## A login form + +```php +$v = new Validation($_POST); + +$valid = $v + ->rule('email', 'required|mail') + ->rule('password', 'required') + ->validation(); +``` + +## A REST API JSON payload + +```php +$payload = json_decode((string) file_get_contents('php://input'), true) ?? []; + +$v = new Validation($payload); + +$valid = $v + ->rule('title', 'required|string|length(1...120)') + ->rule('body', 'required|string') + ->rule('status', 'only(draft, published, archived)') + ->rule('tags', 'optional|array') + ->rule('published_at', 'optional|dateFormat(Y-m-d)') + ->validation(); + +if (!$valid) { + http_response_code(422); + echo json_encode(['errors' => $v->getError()]); + exit; +} +``` + +## A password change + +```php +$v = new Validation($_POST); + +$valid = $v + ->rule('current_password', 'required') + ->rule('new_password', 'required|length(10...)|notIn(password)') + ->rule('new_password_confirm', 'again(new_password)') + ->validation(); +``` + +## Query-string filters with optional fields + +```php +// GET /products?min_price=10&in_stock=1 +$v = new Validation($_GET); + +$valid = $v + ->rule('min_price', 'optional|numeric|min(0)') + ->rule('max_price', 'optional|numeric|min(0)') + ->rule('in_stock', 'optional|boolean') + ->rule('sort', 'optional|only(price, name, newest)') + ->validation(); +``` + +See [Optional Fields](Optional-Fields.md) for the exact "absent" semantics. + +## A reusable, pre-configured validator + +Configure language, labels and custom rules **once**, then reuse the instance +for many *queue → validate → read* cycles: + +```php +use InitPHP\Validation\Validation; + +$v = new Validation(); +$v->setLocale('en'); +$v->labels([ + 'email' => 'E-mail address', + 'dob' => 'Date of birth', +]); +$v->extend('adult', static function ($value): bool { + return strtotime((string) $value) <= strtotime('-18 years'); +}, '{field} must be 18 or older.'); + +// later, per request: +$v->setData($_POST) + ->rule('email', 'required|mail') + ->rule('dob', 'required|date|adult'); +$ok = $v->validation(); +``` + +Custom rules, patterns, labels and the locale survive `validation()` — only the +rule queue and errors reset. + +## Errors grouped by field + +`getError()` is a flat list. Validate each field on its own run to key the +messages by field: + +```php +function validateFields(Validation $v, array $rules): array +{ + $errors = []; + foreach ($rules as $field => $rule) { + $v->rule($field, $rule); + if (!$v->validation()) { + $errors[$field] = $v->getError(); + } + } + return $errors; +} + +$errors = validateFields(new Validation($_POST), [ + 'username' => 'required|alphanum', + 'email' => 'required|mail', +]); +``` + +## Validate a list of items + +```php +$rows = [ + ['sku' => 'AB-1234', 'qty' => '2'], + ['sku' => 'bad', 'qty' => 'x'], +]; + +$v = new Validation(); +$v->pattern('sku', '[A-Z]{2}-[0-9]{4}'); + +$problems = []; +foreach ($rows as $i => $row) { + $v->setData($row) + ->rule('sku', 'required|regex(sku)') + ->rule('qty', 'required|integer|min(1)'); + if (!$v->validation()) { + $problems[$i] = $v->getError(); + } +} +``` + +## A custom domain rule + +```php +$v = new Validation(['website' => 'https://example.org']); + +$v->extend( + 'httpsUrl', + static fn ($value): bool => is_string($value) && str_starts_with($value, 'https://'), + '{field} must use HTTPS.' +); + +$ok = $v->rule('website', 'required|url|httpsUrl')->validation(); +``` + +## Next + +- [Callable & Custom Rules](Callable-and-Custom-Rules.md) — more on `extend()`. +- [Testing](Testing.md) — test your validation logic. diff --git a/docs/Rules-Reference.md b/docs/Rules-Reference.md new file mode 100644 index 0000000..01bc84a --- /dev/null +++ b/docs/Rules-Reference.md @@ -0,0 +1,361 @@ +# Rules Reference + +Every built-in rule, grouped by purpose. Rules are written in a pipe-separated +DSL string; arguments go in parentheses and are comma-separated and **trimmed** +(`only(a, b)` equals `only(a,b)`). Rule names are matched **case-insensitively** +(`creditCard` and `creditcard` are the same rule). + +All examples assume: + +```php +use InitPHP\Validation\Validation; + +$v = new Validation($data); +``` + +> Need something custom? See [Callable & Custom Rules](Callable-and-Custom-Rules.md). + +## Contents + +- **Presence**: [`required`](#required) · [`optional`](#optional) · [`empty`](#empty) +- **Types**: [`integer`](#integer) · [`float`](#float) · [`numeric`](#numeric) · [`string`](#string) · [`boolean`](#boolean) · [`array`](#array) +- **Text**: [`alpha`](#alpha) · [`alphanum` / `alphanumeric`](#alphanum--alphanumeric) +- **Contact & network**: [`mail`](#mail) · [`mailHost`](#mailhost) · [`url`](#url) · [`urlHost`](#urlhost) · [`ip` / `ipv4` / `ipv6`](#ip--ipv4--ipv6) +- **Size & length**: [`min`](#min) · [`max`](#max) · [`range`](#range) · [`length`](#length) +- **Pattern & format**: [`regex`](#regex) · [`date`](#date) · [`dateFormat`](#dateformat) · [`creditCard`](#creditcard) +- **Comparison**: [`again`](#again) · [`equals`](#equals) · [`startWith`](#startwith) · [`endWith`](#endwith) · [`in`](#in) · [`notIn`](#notin) · [`contains`](#contains) · [`notContains`](#notcontains) · [`only`](#only) · [`strictOnly`](#strictonly) + +--- + +## Presence + +### `required` + +The value is present and not a blank string. Numbers (including `0`) and +non-empty arrays pass; `null`, `''`, whitespace-only strings and empty arrays +fail. + +```php +$v->rule('name', 'required'); +``` + +### `optional` + +A pseudo-rule, not a check. When the field has no value, its other rules are +skipped instead of failing. See [Optional Fields](Optional-Fields.md). + +```php +$v->rule('nickname', 'optional|alpha'); +``` + +### `empty` + +The value is empty once trimmed. + +```php +$v->rule('honeypot', 'empty'); // passes for "", " " +``` + +--- + +## Types + +### `integer` + +An integer or an integer-looking string (`"-12"`, `"12"`). Floats and +non-numeric strings fail. + +### `float` + +A float or int, or a float-looking string (`"13.50"`, `"-2.00"`). Every integer +is also a valid float. + +### `numeric` + +Any numeric value: ints, floats and numeric strings. + +### `string` + +A real string — this checks the **type**, so `12` (int) fails but `"12"` passes. + +### `boolean` + +A real boolean, or one of `true`, `false`, `1`, `0` (as int or string). Other +integers such as `2` fail. + +### `array` + +An array. + +```php +$v->rule('id', 'integer'); +$v->rule('price', 'float'); +$v->rule('active', 'boolean'); +$v->rule('tags', 'array'); +``` + +--- + +## Text + +### `alpha` + +Letters only, Unicode-aware (`\p{L}+`). Spaces and digits fail. + +### `alphanum` / `alphanumeric` + +Letters and digits only. The two names are aliases. + +```php +$v->rule('first_name', 'alpha'); // "José" passes, "John Doe" fails +$v->rule('slug', 'alphanumeric'); // "abc123" passes, "abc 123" fails +``` + +--- + +## Contact & network + +### `mail` + +A valid e-mail address (`FILTER_VALIDATE_EMAIL`). + +### `mailHost` + +`mailHost(host, ...)` — a valid e-mail whose host is one of the given hosts. + +```php +$v->rule('email', 'mailHost(gmail.com, outlook.com)'); +``` + +### `url` + +A valid URL (`FILTER_VALIDATE_URL`). + +### `urlHost` + +`urlHost(domain, ...)` — a URL whose host equals one of the domains, **or is a +subdomain of it**. + +```php +$v->rule('site', 'urlHost(example.com)'); +// passes for http://example.com and http://www.example.com +``` + +### `ip` / `ipv4` / `ipv6` + +A valid IP address of the requested family. + +```php +$v->rule('remote', 'ip'); +$v->rule('gateway', 'ipv4'); +$v->rule('client', 'ipv6'); +``` + +--- + +## Size & length + +For `min`/`max`, **numbers are compared by value** and **strings/arrays by their +length/element count**. `range` is value-only; `length` is length/count-only. + +### `min` + +`min(n)`: + +```php +$v->rule('age', 'min(18)'); // age >= 18 (number) +$v->rule('title', 'min(3)'); // at least 3 characters +$v->rule('items', 'min(1)'); // at least 1 element +``` + +### `max` + +`max(n)`: + +```php +$v->rule('discount', 'max(100)'); +$v->rule('bio', 'max(280)'); +``` + +### `range` + +`range(min...max)` — a number within the range. Also accepts `min-max`, and open +bounds `...max` or `min...`. Negative bounds work with the `...` separator. + +```php +$v->rule('year', 'range(1970...2099)'); +$v->rule('score', 'range(0-10)'); +$v->rule('temp', 'range(-40...60)'); +``` + +### `length` + +`length(spec)` — string length or array element count. `spec` may be: + +- a single number — treated as the **maximum** (`length(255)`), +- a closed range — `length(3...20)` or `length(3-20)`, +- an open range — `length(...255)` (max only) or `length(10...)` (min only). + +```php +$v->rule('username', 'length(3...20)'); +$v->rule('comment', 'length(...500)'); +$v->rule('password', 'length(8...)'); +``` + +--- + +## Pattern & format + +### `regex` + +`regex(name | body)` — matches a [named pattern](Patterns-and-Regex.md) or an +inline regex body (without delimiters). The value is matched anchored as +`^(...)$`. + +```php +$v->rule('email', 'regex(email)'); // built-in named pattern +$v->pattern('code', '[A-Z]{2}-[0-9]{4}'); +$v->rule('product', 'regex(code)'); // your own named pattern +``` + +> Avoid commas inside an inline body — they are parsed as argument separators. +> Register a [named pattern](Patterns-and-Regex.md) instead. + +### `date` + +A `DateTimeInterface` instance, or any string `strtotime()` can parse +(`2022-01-01`, `10 September 2000`, `next Thursday`). + +```php +$v->rule('published_at', 'date'); +``` + +### `dateFormat` + +`dateFormat(format)` — a date string in the given `date()` format. + +```php +$v->rule('published_at', 'dateFormat(Y/m/d)'); // "2022/01/01" passes +``` + +### `creditCard` + +`creditCard(type?)` — a credit card number, ignoring spaces. With no argument any +supported brand passes; with a type, only that brand: `amex`, `visa`, +`mastercard`, `maestro`, `jcb`, `solo`, `switch`. + +```php +$v->rule('card', 'creditCard'); +$v->rule('card', 'creditCard(visa)'); +``` + +--- + +## Comparison + +### `again` + +`again(field)` — loosely equals the value of another field in the data set. +Ideal for password and e-mail confirmation. + +```php +$v->rule('confirm', 'again(password)'); +``` + +### `equals` + +`equals(value)` — loosely equals the given value, so `equals(123)` matches both +`123` and `"123"`. + +```php +$v->rule('agree', 'equals(1)'); +``` + +### `startWith` + +`startWith(value)` — a string that starts with the value, or an array whose +first element equals it. + +```php +$v->rule('phone', 'startWith(+90)'); +``` + +### `endWith` + +`endWith(value)` — a string that ends with the value, or an array whose last +element equals it. + +```php +$v->rule('file', 'endWith(.pdf)'); +``` + +### `in` + +`in(needle)` — for strings/numbers: a **case-insensitive substring** test. For +arrays: **strict membership**. + +```php +$v->rule('text', 'in(dolor)'); // 'dolor' appears in the string +$v->rule('roles', 'in(admin)'); // 'admin' is an element of the array +``` + +### `notIn` + +`notIn(needle)` — the inverse of [`in`](#in). + +```php +$v->rule('text', 'notIn(spam)'); +``` + +### `contains` + +`contains(needle)` — a **case-sensitive** substring test on the string form of +the value. + +```php +$v->rule('text', 'contains(Dolor)'); +``` + +### `notContains` + +`notContains(needle)` — the inverse of [`contains`](#contains). + +```php +$v->rule('text', 'notContains(http)'); +``` + +### `only` + +`only(a, b, ...)` — the value **case-insensitively** equals one of the options. + +```php +$v->rule('size', 'only(small, medium, large)'); // "Medium" passes +``` + +### `strictOnly` + +`strictOnly(a, b, ...)` — the value equals one of the options, **case-sensitive**. + +```php +$v->rule('flag', 'strictOnly(Y, N)'); +``` + +--- + +## Combining rules + +Pipe rules together; they run left to right and each failure adds a message. + +```php +$v->rule('username', 'required|alphanum|length(3...20)'); + +// the same rules for two fields at once +$v->rule('email|backup_email', 'optional|mail'); +``` + +## Next + +- [Optional Fields](Optional-Fields.md) — the `optional` pseudo-rule in depth. +- [Callable & Custom Rules](Callable-and-Custom-Rules.md) — when the built-ins are + not enough. +- [Error Messages](Error-Messages.md) — placeholders, labels and custom messages. diff --git a/docs/Testing.md b/docs/Testing.md new file mode 100644 index 0000000..916c591 --- /dev/null +++ b/docs/Testing.md @@ -0,0 +1,97 @@ +# Testing + +## Running the package's own test suite + +If you cloned the repository, install the dev dependencies and use the Composer +scripts: + +```bash +composer install +composer test # PHPUnit +composer stan # PHPStan (max level) +composer cs-check # PHP-CS-Fixer (dry run) +composer ci # all three: cs-check, stan, test +``` + +`composer cs-fix` applies the coding-style fixes in place. + +## Testing your own validation logic + +Because a validator is just an object, testing your rules is straightforward +PHPUnit. Assert both the boolean result and the messages. + +```php +use InitPHP\Validation\Validation; +use PHPUnit\Framework\TestCase; + +final class RegistrationValidationTest extends TestCase +{ + private function validate(array $data): Validation + { + $v = new Validation($data); + $v->rule('username', 'required|alphanum|length(3...20)') + ->rule('email', 'required|mail') + ->rule('password', 'required|length(8...)') + ->rule('confirm', 'again(password)'); + $v->validation(); + + return $v; + } + + public function testValidPayloadPasses(): void + { + $v = $this->validate([ + 'username' => 'ada', + 'email' => 'ada@example.com', + 'password' => 'sup3rsecret', + 'confirm' => 'sup3rsecret', + ]); + + $this->assertTrue($v->isValid()); + $this->assertSame([], $v->getError()); + } + + public function testMismatchedConfirmFails(): void + { + $v = $this->validate([ + 'username' => 'ada', + 'email' => 'ada@example.com', + 'password' => 'sup3rsecret', + 'confirm' => 'typo', + ]); + + $this->assertFalse($v->isValid()); + } +} +``` + +## Asserting on messages + +Switch to a known locale so message assertions are stable, or assert with your +own custom messages: + +```php +$v = new Validation(['age' => 'abc']); +$v->setLocale('en'); +$v->rule('age', 'integer'); +$v->validation(); + +$this->assertSame(['age must be an integer.'], $v->getError()); +``` + +## Testing a custom rule + +```php +public function testEvenRule(): void +{ + $v = new Validation(['n' => 5]); + $v->extend('even', static fn ($value): bool => ((int) $value % 2) === 0); + + $this->assertFalse($v->rule('n', 'even')->validation()); +} +``` + +## Next + +- [Recipes](Recipes.md) — patterns worth covering with tests. +- [Error Messages](Error-Messages.md) — what to assert against. diff --git a/docs/The-Validation-Lifecycle.md b/docs/The-Validation-Lifecycle.md new file mode 100644 index 0000000..8af3776 --- /dev/null +++ b/docs/The-Validation-Lifecycle.md @@ -0,0 +1,103 @@ +# The Validation Lifecycle + +Understanding the order of operations makes everything else click. A validator +holds four pieces of state: the **data**, a **rule queue**, a list of +**optional** fields, and the **errors** from the last run. + +## Queue → validate → read + +```php +use InitPHP\Validation\Validation; + +$validation = new Validation(['age' => 'abc']); + +$validation->rule('age', 'integer'); // 1. queue +$ok = $validation->validation(); // 2. validate → false +$errors = $validation->getError(); // 3. read → ["age must be an integer."] +``` + +`rule()` does **not** check anything — it only appends to the queue. +`validation()` is what actually runs the checks. + +## What `validation()` does, in order + +1. **Clears the error list.** Each run starts clean. +2. **Runs every queued rule.** For each rule it reads the field value from the + data, runs the check, and appends a message on failure. + [Optional](Optional-Fields.md) fields with no value are skipped. +3. **Empties the rule queue and the optional list.** +4. **Returns** `true` when no rule failed. + +Because step 3 consumes the queue, the natural pattern is **queue → validate → +read, then repeat**: + +```php +$validation->setData(['a' => 'x', 'b' => '5']); + +$validation->rule('a', 'integer'); +$validation->validation(); // checks only 'a' → false + +$validation->rule('b', 'integer'); +$validation->validation(); // checks only 'b' → true (the 'a' rule is gone) +``` + +If you expected the second run to re-check `a`, queue it again — rules are not +sticky. + +## The data API + +| Method | Effect | +| --- | --- | +| `new Validation($data)` | Start with a data set. | +| `setData($data)` | Replace the whole data set. | +| `mergeData($data)` | Merge in values; existing keys are overwritten. | +| `getData()` | Read the current data set back. | + +```php +$validation = new Validation(['a' => 1]); +$validation->mergeData(['b' => 2, 'a' => 3]); +$validation->getData(); // ['a' => 3, 'b' => 2] +``` + +## `validation()` vs `isValid()` + +- `validation()` **runs** the queue and returns the result. +- `isValid()` returns the result of the **last** run without re-running. + +```php +$validation->rule('a', 'integer')->validation(); // runs +$validation->isValid(); // same answer, no re-run +``` + +## Resetting with `clear()` + +`clear()` throws away the queued rules, the optional flags and the errors — +without validating. Registered custom rules, named patterns and the loaded +locale are kept. + +```php +$validation->rule('a', 'integer'); +$validation->clear(); // queue dropped +$validation->validation(); // nothing to check → true +``` + +## What survives a run + +| State | Cleared by `validation()` | Cleared by `clear()` | +| --- | --- | --- | +| Errors | Yes (at the start) | Yes | +| Rule queue | Yes (at the end) | Yes | +| Optional flags | Yes (at the end) | Yes | +| Data | No | No | +| [Custom rules](Callable-and-Custom-Rules.md) (`extend`) | No | No | +| [Named patterns](Patterns-and-Regex.md) (`pattern`) | No | No | +| Loaded [locale](Localization.md) | No | No | + +So register your custom rules, patterns and locale **once** during setup, then +loop over *queue → validate → read* as many times as you like. + +## Next + +- [Rules Reference](Rules-Reference.md) — the full catalogue of checks. +- [Optional Fields](Optional-Fields.md) — how absent fields are handled. +- [Error Messages](Error-Messages.md) — customizing what users see. diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md new file mode 100644 index 0000000..1be421f --- /dev/null +++ b/docs/Troubleshooting.md @@ -0,0 +1,96 @@ +# Troubleshooting + +Concrete symptoms and their fixes. For the bigger picture see +[The Validation Lifecycle](The-Validation-Lifecycle.md). + +## `UndefinedRuleException: The validation rule "..." is not defined.` + +The rule name is unknown. Causes: + +- **A typo** — `integerr`, `requierd`, `lenght`. Fix the spelling. +- **A custom rule used before it was registered** — call + [`extend()`](Callable-and-Custom-Rules.md#named-rules-with-extend) before + `validation()`. +- **A global function name** — 2.0 no longer dispatches to global functions. + Wrap it: `$v->extend('ctype_digit', fn ($x) => ctype_digit((string) $x));` + +## An `optional` field still fails validation + +`optional` skips a field only when it is **missing or `null`**. An empty string +is *present*, so its rules run. + +```php +$v = new Validation(['nick' => '']); +$v->rule('nick', 'optional|alpha'); +$v->validation(); // false — '' is present and not alphabetic +``` + +Guard on the value first, or allow blanks explicitly. See +[Optional Fields](Optional-Fields.md#when-is-a-field-absent). + +## My second `validation()` only checks the new rules + +That is by design — `validation()` consumes the queue each run. Re-queue any +rules you want re-checked. See +[The Validation Lifecycle](The-Validation-Lifecycle.md#queue--validate--read). + +## `regex(...)` with a comma in it doesn't work + +DSL arguments are split on commas, so an inline body like `[a-z]{2,4}` is broken +apart. Register it as a [named pattern](Patterns-and-Regex.md#named-patterns) +instead: + +```php +$v->pattern('two_to_four', '[a-z]{2,4}'); +$v->rule('code', 'regex(two_to_four)'); +``` + +## `in()` on an array of integers returns false + +Array membership is **strict**, and DSL arguments are always strings, so +`in(2)` looks for the string `"2"`, not the integer `2`. + +```php +$v = new Validation(['ids' => [1, 2, 3]]); +$v->rule('ids', 'in(2)'); // false — "2" !== 2 +``` + +For typed arrays, use a [callback rule](Callable-and-Custom-Rules.md#callback-rules): + +```php +$v->rule('ids', static fn ($value): bool => in_array(2, (array) $value, true)); +``` + +## The message shows the raw field name (`user_email`) + +Register a friendly label: + +```php +$v->labels(['user_email' => 'E-mail address']); +``` + +See [Error Messages](Error-Messages.md#labels). + +## `LocaleException` when calling `setLocale()` + +The language file was not found. Check that the file exists at +`/.php` and returns an array. Point at a custom directory +with [`setLocaleDir()`](API-Reference.md#setlocaledir) before `setLocale()`. + +## A manually `setError()`'d message disappeared + +`validation()` clears the error list at the **start** of each run. Add manual +errors *after* validating, or in a flow that does not call `validation()` again. +See [Error Messages](Error-Messages.md#adding-a-message-manually). + +## `min`/`max` measured length when I meant the number + +For a numeric value, `min`/`max` compare the **value**; for a non-numeric string +they compare the **length**. A numeric string is treated as a number. If you +always want length, use [`length`](Rules-Reference.md#length); for a value range use +[`range`](Rules-Reference.md#range). + +## Next + +- [FAQ](FAQ.md) — conceptual questions. +- [Exceptions](Exceptions.md) — what each exception means. diff --git a/docs/_Footer.md b/docs/_Footer.md new file mode 100644 index 0000000..35e8e07 --- /dev/null +++ b/docs/_Footer.md @@ -0,0 +1,8 @@ +**`initphp/validation`** · MIT License · part of the [InitPHP](https://github.com/InitPHP) family + +[Source](https://github.com/InitPHP/Validation) · +[Issues](https://github.com/InitPHP/Validation/issues) · +[Discussions](https://github.com/orgs/InitPHP/discussions) · +[Packagist](https://packagist.org/packages/initphp/validation) · +[Contributing](https://github.com/InitPHP/.github/blob/main/CONTRIBUTING.md) · +[Security Policy](https://github.com/InitPHP/.github/blob/main/SECURITY.md) diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md new file mode 100644 index 0000000..7373141 --- /dev/null +++ b/docs/_Sidebar.md @@ -0,0 +1,31 @@ +### [Home](Home.md) + +**Getting Started** +- [Installation](Installation.md) +- [Quick Start](Quick-Start.md) +- [The Validation Lifecycle](The-Validation-Lifecycle.md) + +**Rules** +- [Rules Reference](Rules-Reference.md) +- [Optional Fields](Optional-Fields.md) + +**Extending** +- [Callable & Custom Rules](Callable-and-Custom-Rules.md) +- [Patterns & Regex](Patterns-and-Regex.md) + +**Messages** +- [Error Messages](Error-Messages.md) +- [Localization](Localization.md) + +**Reference** +- [API Reference](API-Reference.md) +- [Exceptions](Exceptions.md) + +**Guides** +- [Recipes](Recipes.md) +- [Testing](Testing.md) + +**Other** +- [Migration from 1.x](Migration-from-1.x.md) +- [FAQ](FAQ.md) +- [Troubleshooting](Troubleshooting.md) diff --git a/docs/api-reference.md b/docs/api-reference.md deleted file mode 100644 index 6486c1a..0000000 --- a/docs/api-reference.md +++ /dev/null @@ -1,111 +0,0 @@ -# API reference - -All methods live on `InitPHP\Validation\Validation`. Every setter returns -`$this` for chaining unless noted otherwise. - -## Data - -### `__construct(array $data = [])` - -Create a validator with an optional initial data set. - -### `setData(array $data = []): self` - -Replace the entire data set. - -### `mergeData(array $data = []): self` - -Merge values into the current data set. Existing keys are overwritten. - -### `getData(): array` - -Return the current data set. - -## Rules - -### `rule(string|array $key, string|callable|array $rule, ?string $err = null): self` - -Queue one or more rules for one or more fields. - -- `$key` — a field name, a pipe-separated list (`"a|b"`), or an array of names. -- `$rule` — a pipe-separated DSL string, a callable, or an array mixing both. - The pseudo-rule `optional` marks the field(s) as allowed to be absent. -- `$err` — an optional custom message template for these rules. - -Throws `Exception\InvalidArgumentException` if a key or rule entry has an -unsupported type. - -### `extend(string $name, callable $callback, ?string $message = null): self` - -Register a custom named rule usable from the DSL string. The callback receives -the value followed by any rule arguments and returns a boolean. Registered rules -persist across runs. - -### `pattern(string $name, string $pattern = '[\w]+'): self` - -Register or override a named pattern for the `regex` rule. Names are -case-insensitive; the body has no delimiters and is matched as `^(...)$`. - -## Running - -### `validation(): bool` - -Evaluate every queued rule. Clears the error list, runs each rule (skipping -optional absent fields), then empties the rule and optional queues. Returns -`true` when nothing failed. - -Throws `Exception\UndefinedRuleException` if a string rule names a rule that is -neither built-in nor registered with `extend()`. - -### `isValid(): bool` - -Return whether the most recent `validation()` run had no errors, without -re-running. - -### `clear(): self` - -Drop queued rules, optional flags and errors. Registered rules, patterns and the -loaded locale are kept. - -## Errors - -### `getError(): array` - -Return the list of messages from the most recent `validation()` run. - -### `setError(string $error, array $context = []): self` - -Append an interpolated message to the current error list. Note `validation()` -resets the list at the start of each run. - -## Localization - -### `setLocale(string $locale = 'en'): self` - -Load `.php` from the locale directory and merge it over the active -messages. Throws `Exception\LocaleException` if the file is missing or does not -return an array. - -### `setLocaleDir(string $dir = …): self` - -Set the directory language files are loaded from. Throws -`Exception\LocaleException` if the directory does not exist. - -### `setLocaleArray(array $assoc): self` - -Merge a partial set of message templates over the active locale. - -### `labels(array $assoc): self` - -Register display labels that replace raw field names in messages. - -## Misc - -### `version(): string` - -Return the library version (`Validation::VERSION`). - -## Exceptions - -See [exceptions](exceptions.md). All implement -`InitPHP\Validation\Exception\ExceptionInterface`. diff --git a/docs/custom-rules-and-callables.md b/docs/custom-rules-and-callables.md deleted file mode 100644 index 162e3f5..0000000 --- a/docs/custom-rules-and-callables.md +++ /dev/null @@ -1,85 +0,0 @@ -# Custom rules & callables - -When the built-in rules are not enough, there are three ways to add your own -logic: callback rules, mixed rule arrays, and registered named rules. - -## Callback rules - -Pass a callable as the rule. It receives the field value and returns a boolean. -The third argument to `rule()` is the message used when it returns `false`. - -```php -use InitPHP\Validation\Validation; - -$v = new Validation(['number' => 13]); - -$v->rule('number', static function ($value): bool { - return ($value % 2) === 0; -}, '{field} must be an even number.'); - -$v->validation(); // false -$v->getError(); // ["number must be an even number."] -``` - -The callback is always called with the field value, or `null` when the field is -absent. Without a custom message, a failed callback uses the generic -`callable` message ("The {field} value is not valid."). - -## Mixed rule arrays - -A rule can be an array that mixes DSL strings and callbacks. They run in order. - -```php -$v->rule('quantity', [ - 'required', - 'integer', - static fn ($value): bool => $value > 0, -]); -``` - -## Named rules with `extend()` - -Callbacks are per-field. To reuse a rule across fields — and use it inside a DSL -string with arguments — register it with `extend()`: - -```php -$v->extend( - 'divisible', - static fn ($value, $by): bool => ((int) $value % (int) $by) === 0, - '{field} must be divisible by {2}.' -); - -$v->rule('quantity', 'divisible(5)'); -$v->rule('weight', 'divisible(10)'); -``` - -`extend(string $name, callable $callback, ?string $message = null)`: - -- `$name` is matched case-insensitively, like the built-in rules. -- `$callback` receives the value followed by any DSL arguments (as strings) and - returns a boolean. -- `$message` is optional; when given, it becomes the template for that rule and - can use `{field}` and positional placeholders. - -Registered rules persist across `validation()` runs and are **not** cleared by -`clear()`, so register them once during setup: - -```php -$v->extend('even', static fn ($value): bool => ((int) $value % 2) === 0); - -$v->setData(['a' => 4])->rule('a', 'even')->validation(); // true -$v->setData(['a' => 5])->rule('a', 'even')->validation(); // false -``` - -A registered rule can also override a built-in one by using the same name. - -## Which one to use? - -| Need | Use | -| ---- | --- | -| One-off check for a single field | Callback rule | -| Several checks, some custom, on one field | Mixed rule array | -| A reusable rule shared across fields, usable in the DSL string | `extend()` | - -See also [localization & messages](localization-and-messages.md) for message -placeholders. diff --git a/docs/exceptions.md b/docs/exceptions.md deleted file mode 100644 index 7ca4fe1..0000000 --- a/docs/exceptions.md +++ /dev/null @@ -1,73 +0,0 @@ -# Exceptions - -Every exception thrown by the package lives under -`InitPHP\Validation\Exception` and implements the marker interface -`ExceptionInterface`, so you can catch them all at once. - -``` -Throwable -└── ExceptionInterface (interface) - ├── ValidationException (extends RuntimeException) - │ ├── UndefinedRuleException - │ └── LocaleException - └── InvalidArgumentException (extends \InvalidArgumentException) -``` - -## `UndefinedRuleException` - -Thrown by `validation()` when a string rule names a rule that is neither -built-in nor registered with `extend()`. Unknown rules fail loudly rather than -silently passing — a misspelled rule is a bug, not a valid field. - -```php -use InitPHP\Validation\Exception\UndefinedRuleException; - -$v->rule('age', 'integerr'); // typo -try { - $v->validation(); -} catch (UndefinedRuleException $e) { - // 'The validation rule "integerr" is not defined.' -} -``` - -## `InvalidArgumentException` - -Thrown by `rule()` when a key or rule entry has an unsupported type — for -example an array rule entry that is neither a string nor a callable. It extends -the SPL `\InvalidArgumentException` and also implements `ExceptionInterface`. - -```php -$v->rule('age', [123]); // 123 is not a string or callable → thrown here -``` - -## `LocaleException` - -Thrown by `setLocale()` and `setLocaleDir()` when a locale cannot be loaded: the -directory does not exist, the file is missing, or the file does not return an -array. - -```php -use InitPHP\Validation\Exception\LocaleException; - -try { - $v->setLocale('xx'); -} catch (LocaleException $e) { - // could not find the language file -} -``` - -## Catching everything - -```php -use InitPHP\Validation\Exception\ExceptionInterface; - -try { - $v->rule('age', 'integer')->validation(); -} catch (ExceptionInterface $e) { - // any failure originating from InitPHP Validation -} -``` - -Note that a failed **validation** is not an exception — it is the normal -`false` return of `validation()`, with messages in `getError()`. Exceptions are -reserved for configuration and programming errors. diff --git a/docs/getting-started.md b/docs/getting-started.md deleted file mode 100644 index cd0402f..0000000 --- a/docs/getting-started.md +++ /dev/null @@ -1,109 +0,0 @@ -# Getting started - -## Install - -```bash -composer require initphp/validation -``` - -Requires PHP 8.1+ and `ext-mbstring`. - -## The `Validation` object - -Create a validator and give it the data to check. Any associative array works — -`$_POST`, `$_GET`, a decoded JSON body, or a plain array. - -```php -use InitPHP\Validation\Validation; - -$validation = new Validation($_POST); - -// or set/merge data later -$validation->setData(['email' => 'a@b.com']); -$validation->mergeData(['name' => 'Ada']); -``` - -## Queue rules, then validate - -Every `rule()` call queues one or more checks. `validation()` runs the whole -queue and returns a boolean. `rule()` is chainable. - -```php -$valid = $validation - ->rule('email', 'required|mail') - ->rule('name', 'required|alpha') - ->validation(); -``` - -A rule string is a pipe-separated list. The first field of `email` above is -checked for `required` first, then `mail`. - -## Read the errors - -`getError()` returns the messages produced by the **most recent** -`validation()` call. - -```php -if (!$valid) { - foreach ($validation->getError() as $message) { - echo $message, "\n"; - } -} -``` - -`isValid()` returns the boolean result of that same run without re-running it. - -## The validation lifecycle - -`validation()` does three things in order: - -1. Clears the error list. -2. Runs every queued rule (skipping [optional](optional-and-patterns.md) fields - that have no value). -3. Empties the rule queue. - -Because the queue is consumed, the natural pattern is **queue → validate → read, -then repeat**: - -```php -$validation->rule('a', 'integer'); -$validation->validation(); // checks only 'a' - -$validation->rule('b', 'integer'); -$validation->validation(); // checks only 'b' -``` - -Call `clear()` to drop any queued rules, optional flags and errors without -validating. - -## A full example - -```php -require 'vendor/autoload.php'; - -use InitPHP\Validation\Validation; - -$validation = new Validation([ - 'username' => 'ada', - 'email' => 'ada@example.com', - 'password' => 'sup3rsecret', - 'confirm' => 'sup3rsecret', - 'age' => '34', -]); - -$valid = $validation - ->rule('username', 'required|alphanum|length(3...20)') - ->rule('email', 'required|mail') - ->rule('password', 'required|length(8...)') - ->rule('confirm', 'again(password)') - ->rule('age', 'optional|integer|range(18...120)') - ->validation(); - -if ($valid) { - // persist the user -} else { - $errors = $validation->getError(); -} -``` - -Next: the [rules reference](rules-reference.md). diff --git a/docs/localization-and-messages.md b/docs/localization-and-messages.md deleted file mode 100644 index 4977e10..0000000 --- a/docs/localization-and-messages.md +++ /dev/null @@ -1,105 +0,0 @@ -# Localization & messages - -## Placeholders - -Message templates support two kinds of placeholder: - -- `{field}` — the field name (passed through [labels](#labels) if one is set). -- Positional `{0}`, `{1}`, `{2}`, ... — `{1}` is the field value and `{2}` is - the first rule argument, `{3}` the second, and so on. - -```php -use InitPHP\Validation\Validation; - -$v = new Validation(['age' => 5]); -$v->rule('age', 'min(18)'); -$v->validation(); -$v->getError(); // ["age must be greater than or equal to 18."] ({2} = 18) -``` - -## Per-rule custom messages - -The third argument to `rule()` overrides the message for that call. It is -interpolated with the same placeholders. - -```php -$v->rule('age', 'min(18)', '{field} is too young (min {2}).'); -// "age is too young (min 18)." -``` - -## Labels - -`labels()` maps raw field names to friendly display names. Only `{field}` is -passed through labels — rule arguments are never label-substituted. - -```php -$v->labels(['age' => 'Age', 'email' => 'E-mail address']); -$v->rule('age', 'min(18)'); -// "Age must be greater than or equal to 18." -``` - -## Switching language - -The package ships with `en` (the default) and `tr`. `setLocale()` loads a -language file and merges it over the active messages. - -```php -$v->setLocale('tr'); -$v->rule('age', 'integer'); -// "age bir tam sayı olmalıdır." -``` - -## Overriding individual messages - -`setLocaleArray()` merges a partial set of templates over the active locale — -useful for tweaking a few messages without a whole language file. - -```php -$v->setLocaleArray([ - 'integer' => '{field} must be a whole number.', - 'required' => 'Please fill in {field}.', -]); -``` - -Message keys are matched case-insensitively against rule names, so a key of -`creditCard` or `creditcard` both apply to the `creditCard` rule. - -## Using your own language directory - -`setLocaleDir()` points the loader at a directory of `.php` files. Each -file returns an associative array of templates. - -```php -$v->setLocaleDir(__DIR__ . '/lang'); -$v->setLocale('de'); // loads __DIR__/lang/de.php -``` - -A language file looks like this: - -```php - '{field} darf nicht leer sein.', - 'integer' => '{field} muss eine Ganzzahl sein.', - 'mail' => '{field} muss eine E-Mail-Adresse sein.', - // ... one entry per rule you want to translate -]; -``` - -Any rule without a matching key falls back to the `notValidDefault` template -("The {field} value is not valid."). The full list of keys is in -[`src/languages/en.php`](../src/languages/en.php). - -## Manually adding an error - -`setError()` appends a message to the current error list, interpolating any -context you pass: - -```php -$v->setError('{field} could not be processed.', ['field' => 'avatar']); -``` - -Note that `validation()` clears the error list at the start of each run, so add -manual errors *after* validating (or in a flow that does not call -`validation()` again). diff --git a/docs/optional-and-patterns.md b/docs/optional-and-patterns.md deleted file mode 100644 index e5539cd..0000000 --- a/docs/optional-and-patterns.md +++ /dev/null @@ -1,87 +0,0 @@ -# Optional fields & patterns - -## The `optional` pseudo-rule - -`optional` is not a check — it marks a field as allowed to be absent. When the -field has no value (it is missing or `null`), every other rule queued for it is -skipped. When the field is present, the other rules apply normally. - -```php -use InitPHP\Validation\Validation; - -$v = new Validation([]); // no 'nickname' key -$v->rule('nickname', 'optional|alpha'); -$v->validation(); // true — skipped - -$v = new Validation(['nickname' => '123']); -$v->rule('nickname', 'optional|alpha'); -$v->validation(); // false — present but not alphabetic -``` - -A field counts as "absent" when its key is missing or its value is `null`. An -empty string (`''`) is considered present, so pair `optional` with `empty` or a -length rule if you want to allow blanks. - -## The validation lifecycle and `optional` - -`validation()` consumes the queued rules **and** the optional flags at the end -of each run, so an `optional` mark only applies to the run it was added in: - -```php -$v = new Validation([]); - -$v->rule('email', 'optional|required'); -$v->validation(); // true — email is optional this run - -$v->rule('email', 'required'); -$v->validation(); // false — optional did not carry over -``` - -This keeps each *queue → validate* cycle independent. Use `clear()` to discard a -queue (rules, optional flags and errors) without validating. - -## Named patterns - -The `regex` rule accepts either an inline regex body or the name of a pattern. -Built-in pattern names: - -| Name | Matches | -| ---- | ------- | -| `uri` | URI path characters | -| `slug` | URL slug characters | -| `url` | URL characters | -| `alpha` | Unicode letters | -| `words` | Letters and whitespace | -| `alphanum` | Letters and digits | -| `int` | Digits | -| `float` | Digits, dot and comma | -| `tel` | Phone-number characters | -| `text` | Common prose characters | -| `file` | A file name with extension | -| `folder` | A folder name | -| `address` | Street-address characters | -| `date_dmy` | `d-m-Y` style dates | -| `date_ymd` | `Y-m-d` style dates | -| `email` | A basic e-mail shape | - -```php -$v->rule('handle', 'regex(slug)'); -``` - -### Registering your own pattern - -`pattern(string $name, string $body)` adds or overrides a named pattern. The -body is a regular expression **without** delimiters; it is matched anchored as -`^(...)$`. - -```php -$v->pattern('product_code', '[A-Z]{2}-[0-9]{4}'); -$v->rule('code', 'regex(product_code)'); -``` - -Pattern names are matched case-insensitively. Registered patterns persist across -`validation()` runs. - -> Because DSL arguments are split on commas, an inline body containing a comma -> (e.g. `[a-z]{2,4}`) will not parse correctly inside `regex(...)`. Register it -> as a named pattern instead. diff --git a/docs/rules-reference.md b/docs/rules-reference.md deleted file mode 100644 index 592e36e..0000000 --- a/docs/rules-reference.md +++ /dev/null @@ -1,283 +0,0 @@ -# Rules reference - -A rule string is a pipe-separated list of rules. Arguments go in parentheses -and are comma-separated; each argument is trimmed, so `only(a, b)` equals -`only(a,b)`. Rule names are matched case-insensitively (`creditCard` and -`creditcard` are the same rule). - -All examples below assume: - -```php -use InitPHP\Validation\Validation; - -$v = new Validation($data); -``` - -## Presence - -### `required` - -The value is present and not a blank string. Numbers (including `0`) and -non-empty arrays pass; `null`, `''`, whitespace-only strings and empty arrays -fail. - -```php -$v->rule('name', 'required'); -``` - -### `optional` - -A pseudo-rule, not a check. When the field has no value, its other rules are -skipped instead of failing. When the field is present, the other rules apply. - -```php -$v->rule('nickname', 'optional|alpha'); -``` - -See [Optional fields & patterns](optional-and-patterns.md). - -### `empty` - -The value is empty once trimmed. - -```php -$v->rule('honeypot', 'empty'); -``` - -## Types - -### `integer` - -An integer or an integer-looking string (`"-12"`, `"12"`). - -### `float` - -A float or int, or a float-looking string (`"13.50"`, `"-2.00"`). Every integer -is also a valid float. - -### `numeric` - -Any numeric value: ints, floats and numeric strings. - -### `string` - -A real string. This checks the **type**, so `12` (int) fails but `"12"` passes. - -### `boolean` - -A real boolean, or one of `true`, `false`, `1`, `0` (as int or string). - -### `array` - -An array. - -```php -$v->rule('id', 'integer'); -$v->rule('price', 'float'); -$v->rule('tags', 'array'); -``` - -## Text - -### `alpha` - -Letters only, Unicode-aware (`[\p{L}]+`). Spaces and digits fail. - -### `alphanum` / `alphanumeric` - -Letters and digits only. The two names are aliases. - -```php -$v->rule('first_name', 'alpha'); -$v->rule('slug', 'alphanumeric'); -``` - -## Contact & network - -### `mail` - -A valid e-mail address (`FILTER_VALIDATE_EMAIL`). - -### `mailHost(host, ...)` - -A valid e-mail whose host is one of the given hosts. - -```php -$v->rule('email', 'mailHost(gmail.com, outlook.com)'); -``` - -### `url` - -A valid URL (`FILTER_VALIDATE_URL`). - -### `urlHost(domain, ...)` - -A URL whose host equals one of the domains, or is a subdomain of it. - -```php -$v->rule('site', 'urlHost(example.com)'); -// passes for http://example.com and http://www.example.com -``` - -### `ip` / `ipv4` / `ipv6` - -A valid IP address of the requested family. - -```php -$v->rule('remote', 'ip'); -$v->rule('gateway', 'ipv4'); -``` - -## Size & length - -For `min`/`max`, numbers are compared by value and strings/arrays by their -length/element count. `range` is value-only; `length` is length/count-only. - -### `min(n)` - -```php -$v->rule('age', 'min(18)'); // age >= 18 (number) -$v->rule('title', 'min(3)'); // at least 3 characters -$v->rule('items', 'min(1)'); // at least 1 element -``` - -### `max(n)` - -```php -$v->rule('discount', 'max(100)'); -$v->rule('bio', 'max(280)'); -``` - -### `range(min...max)` - -A number within the range. Accepts `min-max` as well, and open bounds with -`...max` or `min...`. - -```php -$v->rule('year', 'range(1970...2099)'); -$v->rule('score', 'range(0-10)'); -$v->rule('temp', 'range(-40...60)'); -``` - -### `length(spec)` - -String length or array element count. `spec` may be: - -- a single number — treated as the **maximum** (`length(255)`), -- a closed range — `length(3...20)` or `length(3-20)`, -- an open range — `length(...255)` (max only) or `length(10...)` (min only). - -```php -$v->rule('username', 'length(3...20)'); -$v->rule('comment', 'length(...500)'); -``` - -## Pattern & format - -### `regex(name | body)` - -Matches a [named pattern](optional-and-patterns.md#named-patterns) or an inline -regex body (without delimiters). - -```php -$v->rule('email', 'regex(email)'); // built-in named pattern -$v->pattern('code', '[A-Z]{2}-[0-9]{4}'); -$v->rule('product', 'regex(code)'); // custom named pattern -``` - -> Inline bodies are matched as `^(...)$`. Avoid commas inside an inline body — -> they are parsed as argument separators; register a named pattern instead. - -### `date` - -A `DateTimeInterface` instance, or any string `strtotime()` can parse -(`2022-01-01`, `10 September 2000`, `next Thursday`). - -### `dateFormat(format)` - -A date string in the given `date()` format. - -```php -$v->rule('published_at', 'dateFormat(Y/m/d)'); -``` - -### `creditCard(type?)` - -A credit card number, ignoring spaces. With no argument, any supported brand -passes. With a type, only that brand passes: `amex`, `visa`, `mastercard`, -`maestro`, `jcb`, `solo`, `switch`. - -```php -$v->rule('card', 'creditCard'); -$v->rule('card', 'creditCard(visa)'); -``` - -## Comparison - -### `again(field)` - -Loosely equals the value of another field in the data set — handy for password -and e-mail confirmation. - -```php -$v->rule('confirm', 'again(password)'); -``` - -### `equals(value)` - -Loosely equals the given value. - -```php -$v->rule('agree', 'equals(1)'); -``` - -### `startWith(value)` / `endWith(value)` - -A string that starts/ends with the value. For arrays, compares the first/last -element. - -```php -$v->rule('phone', 'startWith(+90)'); -$v->rule('file', 'endWith(.pdf)'); -``` - -### `in(needle)` / `notIn(needle)` - -For strings/numbers: a case-insensitive substring test. For arrays: strict -membership. - -```php -$v->rule('text', 'in(dolor)'); // 'dolor' appears in the string -$v->rule('roles', 'in(admin)'); // 'admin' is an element of the array -$v->rule('text', 'notIn(spam)'); -``` - -### `contains(needle)` / `notContains(needle)` - -A case-sensitive substring test on the string form of the value. - -```php -$v->rule('text', 'contains(Dolor)'); -$v->rule('text', 'notContains(http)'); -``` - -### `only(a, b, ...)` / `strictOnly(a, b, ...)` - -The value must equal one of the options. `only` is case-insensitive; -`strictOnly` is case-sensitive. - -```php -$v->rule('size', 'only(small, medium, large)'); -$v->rule('flag', 'strictOnly(Y, N)'); -``` - -## Combining rules - -Pipe rules together; they run left to right and each failure adds a message. - -```php -$v->rule('username', 'required|alphanum|length(3...20)'); -$v->rule('email|backup_email', 'optional|mail'); // both fields, same rules -``` - -Continue with [custom rules & callables](custom-rules-and-callables.md).