PHPackages                             mb4it/validation - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. mb4it/validation

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

mb4it/validation
================

Framework-agnostic validation with flexible rules and translation

1.0.2(1mo ago)04MITPHPPHP &gt;=8.2

Since Feb 16Pushed 1mo agoCompare

[ Source](https://github.com/Dictator90/mb-validation)[ Packagist](https://packagist.org/packages/mb4it/validation)[ Docs](https://github.com/mb4it/validation)[ RSS](/packages/mb4it-validation/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (25)Versions (5)Used By (0)

MB Validation
=============

[](#mb-validation)

[Русская версия](ru.README.md)

Framework-agnostic validation library inspired by Laravel-style rules, without coupling to a framework.

Features
--------

[](#features)

- String rules (`required|string|min:3`)
- Object and closure rules
- Localized messages (`ru` / `en`)
- Wildcard array rules (`items.*.name`)
- Strict handling of unknown string rules (fail-fast)
- Optional file-like validation without requiring `symfony/http-foundation`

Installation
------------

[](#installation)

```
composer require mb4it/validation
```

`symfony/http-foundation` is optional.
File-related rules work with file-like objects that expose methods such as:

- `getSize()`
- `getPath()` or `getRealPath()`
- `guessExtension()`
- `getMimeType()`

Quick Start
-----------

[](#quick-start)

```
use MB\Validation\Factory;

$factory = Factory::create(lang: 'en'); // or 'ru'

$validator = $factory->make(
    ['name' => 'John', 'age' => 30],
    ['name' => 'required|string|min:3', 'age' => 'required|integer|between:18,99']
);

if ($validator->fails()) {
    $errors = $validator->errors()->toArray();
} else {
    $validated = $validator->validated();
}
```

Factory API
-----------

[](#factory-api)

### Create Factory

[](#create-factory)

```
use MB\Validation\Factory;

$factory = Factory::create(lang: 'ru');
```

Signature:

```
Factory::create(
    ?MessagesInterface $message = null,
    ?ContainerInterface $container = null,
    string $lang = 'ru'
)
```

If `MessagesInterface` is not provided, factory uses `DefaultMessages::create($lang)`.

### One-shot Validation

[](#one-shot-validation)

```
$validated = $factory->validate($data, $rules, $messages = [], $attributes = []);
```

`validate()` throws `MB\Validation\ValidationException` if validation fails.

### Strict Mode

[](#strict-mode)

Unknown string rules throw `InvalidArgumentException` by default.

Use backward-compatible mode if needed:

```
$factory = Factory::create()->allowUnknownRules();
```

Supported Rule Groups
---------------------

[](#supported-rule-groups)

- Presence / structure: `required`, `required_if`, `required_unless`, `required_array_keys`, `filled`, `array`, `list`, `boolean`
- Type: `string`, `numeric`, `integer`, `decimal`
- Size: `min`, `max`, `between`, `size`, `digits`, `digits_between`
- String: `alpha`, `alpha_num`, `alpha_dash`, `contains`, `doesnt_contain`, `starts_with`, `ends_with`, `doesnt_start_with`, `doesnt_end_with`, `uppercase`, `lowercase`, `ascii`
- Format / network: `email`, `url`, `ip`, `ipv4`, `ipv6`, `mac_address`, `hex_color`, `uuid`, `ulid`, `json`
- Date / time: `date`, `date_format`, `timezone`
- Set / comparison: `in`, `not_in`, `same`, `different`, `prohibited`, `any_of`
- Database: `exists`, `unique` (requires `PresenceVerifierInterface`)

Messages and Localization
-------------------------

[](#messages-and-localization)

Default files:

- `lang/en/validation.php`
- `lang/ru/validation.php`

Message resolution order:

1. Inline messages passed to `make()` / `validate()`
2. Validator fallback custom messages
3. Translator (`MessagesInterface`)

Inline message example:

```
$validator = $factory->make(
    ['email' => null],
    ['email' => 'required|email'],
    ['email.required' => 'We need your email address.']
);
```

Validate Object Properties via Trait
------------------------------------

[](#validate-object-properties-via-trait)

Use `MB\Validation\Concerns\ValidatesProperties` for DTO/value object validation.

Trait behavior:

- collects initialized public/protected/private properties via reflection
- supports wildcard keys (`items.*.name`, `profile.tags.*`)
- validates with `Factory::create(lang: $this->validatorLang)`

### Example

[](#example)

```
use MB\Validation\Concerns\ValidatesProperties;

final class ProductDto
{
    use ValidatesProperties;

    protected string $validatorLang = 'ru'; // optional

    public function __construct(
        public string $title,
        protected array $items,
        private array $profile,
    ) {}

    protected function rules(): array
    {
        return [
            'title' => 'required|string|min:3',
            'items' => 'required|array|min:1',
            'items.*.name' => 'required|string',
            'profile.tags.*' => 'required|string',
        ];
    }
}

$dto = new ProductDto(
    title: 'Notebook',
    items: [['name' => 'A4'], ['name' => 'A5']],
    profile: ['tags' => ['office', 'paper']]
);

$validated = $dto->validate();
```

### Get Errors with Trait

[](#get-errors-with-trait)

`validate()` throws `ValidationException`:

```
use MB\Validation\ValidationException;

try {
    $validated = $dto->validate();
} catch (ValidationException $e) {
    $errors = $e->errors(); // ['field' => ['message1', ...]]
}
```

For non-throwing flow, expose a validator helper in your class:

```
use MB\Validation\Factory;
use MB\Validation\Validator;

public function validator(): Validator
{
    return Factory::create(lang: $this->validatorLang)->make(
        $this->validationData(),
        $this->rules()
    );
}
```

`exists` / `unique` and Presence Verifier
-----------------------------------------

[](#exists--unique-and-presence-verifier)

```
use MB\Validation\Factory;
use MB\Validation\PresenceVerifierInterface;

final class MyPresenceVerifier implements PresenceVerifierInterface
{
    public function getCount($collection, $column, $value, $excludeId = null, $idColumn = null, array $extra = [])
    {
        return 0;
    }

    public function getMultiCount($collection, $column, array $values, array $extra = [])
    {
        return 0;
    }
}

$factory = Factory::create();
$factory->setPresenceVerifier(new MyPresenceVerifier());
```

Custom Rules
------------

[](#custom-rules)

### Closure Rule

[](#closure-rule)

```
use MB\Validation\Validator;

$validator = $factory->make(
    ['field' => 'bad'],
    [
        'field' => [
            function (string $attribute, mixed $value, callable $fail, Validator $validator): void {
                if ($value === 'bad') {
                    $fail($attribute, 'Custom closure rule failed');
                }
            },
        ],
    ]
);
```

### Class-based Rule

[](#class-based-rule)

Implement `MB\Validation\Contracts\ValidationRule` and register your alias in rule registry.

Testing
-------

[](#testing)

```
composer test
```

or

```
vendor/bin/phpunit -c phpunit.xml.dist
```

License
-------

[](#license)

MIT (see `LICENSE`).

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance90

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~42 days

Total

3

Last Release

51d ago

PHP version history (2 changes)1.0.0PHP &gt;=8.1

1.0.1PHP &gt;=8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/75324054?v=4)[Maxim Bezvodinskikh](/maintainers/Dictator90)[@Dictator90](https://github.com/Dictator90)

---

Top Contributors

[![Dictator90](https://avatars.githubusercontent.com/u/75324054?v=4)](https://github.com/Dictator90 "Dictator90 (10 commits)")

---

Tags

phpvalidatorvalidation

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mb4it-validation/health.svg)

```
[![Health](https://phpackages.com/badges/mb4it-validation/health.svg)](https://phpackages.com/packages/mb4it-validation)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.8k543.8M20.1k](/packages/laravel-framework)[illuminate/validation

The Illuminate Validation package.

18838.2M1.7k](/packages/illuminate-validation)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6942.5M421](/packages/drupal-core-recommended)[typo3/cms-core

TYPO3 CMS Core

3713.2M5.1k](/packages/typo3-cms-core)[respect/validation

The most awesome validation engine ever created for PHP

6.0k39.9M415](/packages/respect-validation)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
