Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]

Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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

Expand Down
213 changes: 213 additions & 0 deletions docs/API-Reference.md
Original file line number Diff line number Diff line change
@@ -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 `<locale>.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()`.
126 changes: 126 additions & 0 deletions docs/Callable-and-Custom-Rules.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading