PHPackages                             yorcreative/data-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. [Testing &amp; Quality](/categories/testing)
4. /
5. yorcreative/data-validation

ActiveLibrary[Testing &amp; Quality](/categories/testing)

yorcreative/data-validation
===========================

A lightweight and high-performance PHP validation library designed for enterprise-grade applications. It features zero dependencies, comprehensive test coverage, and a developer-friendly API—enabling teams to build scalable and secure systems with confidence.

v1.0.0(11mo ago)1581[4 PRs](https://github.com/YorCreative/Data-Validation/pulls)MITPHPPHP ^8.3|^8.4CI failing

Since Jun 11Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/YorCreative/Data-Validation)[ Packagist](https://packagist.org/packages/yorcreative/data-validation)[ GitHub Sponsors](https://github.com/yorcreative)[ RSS](/packages/yorcreative-data-validation/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (9)Versions (7)Used By (0)

 [ ![Logo](content/data-validation-logo.png) ](https://github.com/YorCreative)

[![GitHub license](https://camo.githubusercontent.com/bb97d90583937e47f25142acf3cdf047177cfb1fc80e001676fcf4cd1a447146/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f596f7243726561746976652f446174612d56616c69646174696f6e)](https://github.com/YorCreative/Data-Validation/blob/main/LICENSE.md)[![GitHub stars](https://camo.githubusercontent.com/dbc8572a14ae812126b5df9342fcdc21008a0919ccdc5cb8385bb1551aaa8c28/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f596f7243726561746976652f446174612d56616c69646174696f6e3f6c6162656c3d5265706f2532305374617273)](https://github.com/YorCreative/Data-Validation/stargazers)[![GitHub Org's stars](https://camo.githubusercontent.com/c3aef82ca684110e373af0e3676f82fd43ae79ae081691bd87c7e713f993435e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f596f7243726561746976653f7374796c653d736f6369616c266c6162656c3d596f7243726561746976652532305374617273266c696e6b3d68747470732533412532462532466769746875622e636f6d253246596f724372656174697665)](https://camo.githubusercontent.com/c3aef82ca684110e373af0e3676f82fd43ae79ae081691bd87c7e713f993435e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f596f7243726561746976653f7374796c653d736f6369616c266c6162656c3d596f7243726561746976652532305374617273266c696e6b3d68747470732533412532462532466769746875622e636f6d253246596f724372656174697665)[![GitHub issues](https://camo.githubusercontent.com/b819201b281c593f3ec89755cde4df35d1b8e1c7dd6d803bfed571c3a01d3aa4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f596f7243726561746976652f446174612d56616c69646174696f6e)](https://github.com/YorCreative/Data-Validation/issues)[![GitHub forks](https://camo.githubusercontent.com/8adfc288ad3e4214fb97701e812ebd400a1f658d240d3403fddb9b962ea992d9/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f666f726b732f596f7243726561746976652f446174612d56616c69646174696f6e)](https://github.com/YorCreative/Data-Validation/network)[![PHPUnit](https://github.com/YorCreative/Data-Validation/actions/workflows/phpunit.yml/badge.svg)](https://github.com/YorCreative/Data-Validation/actions/workflows/phpunit.yml)

DataValidation is a lightweight, high-performance PHP validation library engineered for enterprise-grade applications. Outperforming alternatives with up to 61.8x faster validation for invalid data, it excels in speed and memory efficiency while seamlessly handling complex nested data with wildcards. With no dependencies, comprehensive test coverage, and a developer-friendly API, DataValidation empowers teams to build scalable, secure systems with confidence.

Why DataValidation?
-------------------

[](#why-datavalidation)

DataValidation sets a new standard for PHP validation with its performance and flexibility:

- **Unmatched Speed**: Validates 5000 items in 1.499 seconds for valid data, up to 5.2x faster than Laravel’s Illuminate\\Validation (7.724 seconds). For invalid data, it’s up to 61.8x faster (1.502 seconds vs. 92.814 seconds).
- **Memory Efficiency**: Maintains a low memory footprint, with peak usage of 10.000 MB for 5000 items, compared to 25.500 MB for alternatives.
- **Wildcard Support**: Effortlessly handles nested arrays with wildcards (e.g., `users.*.email`), ideal for complex API payloads.
- **Extensibility**: Supports custom rules via closures or classes, enabling tailored validation logic.

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

[](#installation)

Install via Composer:

```
composer require yorcreative/data-validation
```

**Requirements**:

- PHP 8.3 or 8.4

Basic Usage
-----------

[](#basic-usage)

Validate data with a clean, intuitive API adhering to PSR-12 standards:

```
use YorCreative\DataValidation\Validator;

$data = [
    'name' => 'John Doe',
    'email' => 'john@example.com'
];
$rules = [
    'name' => 'required|string',
    'email' => 'required|email'
];

$validator = Validator::make($data, $rules);
if ($validator->validate()) {
    echo "Validation passed!";
} else {
    print_r($validator->errors());
}
```

Supported Rules
---------------

[](#supported-rules)

DataValidation provides a comprehensive set of validation rules to meet diverse business needs:

RuleDescriptionExample`string`Must be a string.`'name' => 'string'``numeric`Must be numeric.`'price' => 'numeric'``integer`Must be an integer.`'count' => 'integer'``email`Must be a valid email.`'email' => 'email'``array`Must be an array.`'items' => 'array'``min:value`Minimum value/length.`'age' => 'min:18'``max:value`Maximum value/length.`'age' => 'max:65'``in:a,b,c`Must be one of the listed values.`'role' => 'in:admin,editor'``not_in:a,b,c`Must not be one of the listed values.`'role' => 'not_in:banned'``same:field`Must match another field.`'password_confirmation' => 'same:password'``different:field`Must differ from another field.`'old_password' => 'different:new_password'``date`Must be a valid date.`'dob' => 'date'``regex:pattern`Must match the regex pattern.`'slug' => 'regex:/^[a-z0-9-]+$/'``boolean`Must be a boolean.`'active' => 'boolean'``between:min,max`Must be between two values.`'score' => 'between:1,100'``digits:length`Must be a number with exact digit length.`'phone' => 'digits:10'``starts_with:a,b`Must start with one of the values.`'prefix' => 'starts_with:AB,CD'``ends_with:a,b`Must end with one of the values.`'filename' => 'ends_with:.jpg,.png'``date_format:format`Must match the date format.`'published_at' => 'date_format:Y-m-d'``ip`Must be a valid IP address.`'ip_address' => 'ip'``ipv4`Must be a valid IPv4 address.`'ip' => 'ipv4'``ipv6`Must be a valid IPv6 address.`'ip' => 'ipv6'``url`Must be a valid URL.`'website' => 'url'``json`Must be valid JSON.`'config' => 'json'``uuid`Must be a valid UUID.`'id' => 'uuid'``required`Field must be present and not empty.`'name' => 'required'``nullable`Allows null values, skips other rules if null.`'middle_name' => 'nullable|string'``required_if:field,value`Required if another field equals a value.`'state' => 'required_if:country,US'``required_unless:field,value`Required unless another field equals a value.`'passport' => 'required_unless:citizen,yes'`**Note**: Unknown rules or invalid parameters throw an `InvalidArgumentException` during initialization, ensuring early detection of configuration issues.

Advanced Usage
--------------

[](#advanced-usage)

### Validating Nested Data with Wildcards

[](#validating-nested-data-with-wildcards)

Efficiently validate complex nested data structures using wildcards, ideal for API-driven applications:

```
use YorCreative\DataValidation\Validator;

$data = [
    'users' => [
        ['profile' => ['email' => 'user1@example.com', 'confirm_email' => 'user1@example.com']],
        ['profile' => ['email' => 'user2@example.com', 'confirm_email' => 'user2@example.com']]
    ]
];
$rules = [
    'users.*.profile.email' => 'required|email|same:users.*.profile.confirm_email'
];

$validator = Validator::make($data, $rules);
if ($validator->validate()) {
    echo "All user emails are valid and match their confirmations!";
} else {
    print_r($validator->errors());
}
```

### Custom Validation Rules with Closures

[](#custom-validation-rules-with-closures)

Enable rapid prototyping of business-specific rules using closures:

```
use YorCreative\DataValidation\Validator;

$validator = Validator::make(['score' => 85], [
    'score' => [
        function ($field, $value, $fail) {
            if ($value < 90) {
                $fail("The {$field} must be at least 90 to pass the elite threshold.");
            }
        }
    ]
]);
```

### Custom Error Messages

[](#custom-error-messages)

Tailor error messages to enhance user experience and align with business requirements:

```
use YorCreative\DataValidation\Validator;

$messages = [
    'name.required' => 'Please provide a name.',
    'email.email' => 'Enter a valid email address.'
];
$validator = Validator::make(
    ['name' => '', 'email' => 'invalid'],
    ['name' => 'required', 'email' => 'email'],
    $messages
);
print_r($validator->errors());
```

### Custom Attribute Names

[](#custom-attribute-names)

Improve error message clarity with user-friendly attribute names:

```
use YorCreative\DataValidation\Validator;

$attributes = ['user.email' => 'Email Address', 'user.name' => 'Full Name'];
$validator = Validator::make(
    ['user' => ['email' => 'invalid', 'name' => '']],
    ['user.email' => 'email', 'user.name' => 'required'],
    [],
    $attributes
);
print_r($validator->errors());
```

### Stopping on First Error

[](#stopping-on-first-error)

Optimize performance in latency-sensitive applications by halting validation after the first error:

```
use YorCreative\DataValidation\Validator;

$validator = Validator::make($data, $rules, [], [], true);
if ($validator->fails()) {
    echo "Validation stopped at first error: " . implode(', ', $validator->errors()['user.email']);
}
```

Extending with Custom Rules
---------------------------

[](#extending-with-custom-rules)

For applications requiring bespoke validation logic, implement custom rules via `ValidationRuleInterface`:

```
namespace App\Rules;

use YorCreative\DataValidation\Rules\ValidationRuleInterface;

class PhoneNumberRule implements ValidationRuleInterface
{
    public function validate(string $field, $value, array $parameters, array $data): bool
    {
        return preg_match('/^\+?1?\d{10}$/', $value) === 1;
    }

    public function getErrorMessage(string $field, array $parameters, ?string $customMessage): string
    {
        return $customMessage ?? sprintf('The %s must be a valid US phone number.', $field);
    }

    public function validateParameters(string $field, array $parameters): void
    {
    }
}
```

Register the custom rule directory for seamless integration:

```
use YorCreative\DataValidation\Rules\RuleRegistry;

RuleRegistry::registerCustomRuleDirectory(__DIR__ . '/Rules');
```

Use it in validation workflows:

```
use YorCreative\DataValidation\Validator;

$validator = Validator::make(
    ['phone' => '1234567890'],
    ['phone' => 'required|phone_number']
);
```

Alternatively, register a closure-based rule:

```
use YorCreative\DataValidation\Rules\RuleRegistry;

RuleRegistry::registerClosureRule('phone', function ($value) {
    return preg_match('/^\+?1?\d{10}$/', $value) === 1;
}, 'The :attribute must be a valid US phone number.');
```

Performance Benchmarks
----------------------

[](#performance-benchmarks)

DataValidation is optimized for speed and efficiency, particularly for large datasets and wildcard validations. Benchmarks were conducted on an Apple M1 chip with 10 cores, running PHP 8.4, ensuring optimal conditions for performance evaluation. The following results compare DataValidation (DV) with Laravel's Illuminate\\Validation (IL) across different dataset sizes.

### Benchmark Results for Valid Data

[](#benchmark-results-for-valid-data)

ItemsDV Time (s)DV Mem (MB)IL Time (s)IL Mem (MB)10000.0694.0000.8848.00020000.2496.0002.1124.00030000.5386.0003.5708.00050001.49910.0007.72425.500### Benchmark Results for Invalid Data

[](#benchmark-results-for-invalid-data)

ItemsDV Time (s)DV Mem (MB)IL Time (s)IL Mem (MB)10000.0656.0005.98426.00020000.2554.00016.96436.00030000.5594.00034.39756.00050001.50212.00092.814110.000### Scalability for Large Datasets

[](#scalability-for-large-datasets)

For extremely large datasets, such as 100,000 items, YorCreative\\DataValidation completes validation in approximately 9.2 minutes (553.462 seconds for valid data) with a peak memory usage of 262.012 MB, demonstrating its ability to handle massive amounts of data efficiently. This scalability is crucial for enterprise-grade batch processing, ensuring reliability and performance in production environments.

### Key Definitions

[](#key-definitions)

- **DV (DataValidation)**: The YorCreative\\DataValidation library, optimized for lightweight, high-performance validation tailored to enterprise needs.
- **IL (Illuminate\\Validation)**: Laravel’s validation component, a robust but resource-intensive alternative commonly used in PHP ecosystems.
- **Time (s)**: Time in seconds to validate the dataset.
- **Mem (MB)**: Peak memory usage in megabytes during validation.
- **Items**: Number of records in the dataset (e.g., 1000 users, each with profile and settings data).

### Context and Insights

[](#context-and-insights)

- **Performance Advantage**: DataValidation delivers up to 61.8x faster processing for invalid data (1.502 s vs. 92.814 s for 5000 items) and 5.2x for valid data (1.499 s vs. 7.724 s), reducing latency in critical API endpoints.
- **Memory Efficiency**: Maintains a low memory footprint (10.000 MB peak for 5000 items), compared to Illuminate\\Validation’s 25.500 MB for valid data and 110.000 MB for invalid data, enabling cost-effective scaling.
- **Wildcard Optimization**: Leverages stack-based traversal and caching to handle wildcard rules (e.g., `users.*.email`), addressing performance bottlenecks in Laravel.

### Running Benchmarks

[](#running-benchmarks)

To validate performance in your environment:

```
composer benchmark-all
```

This command executes benchmarks for both DataValidation and Illuminate\\Validation, providing detailed metrics. Ensure sufficient memory (4GB recommended) for accurate results.

Contributing
------------

[](#contributing)

Contributions are welcome! Fork the repository, create a feature branch, and submit a pull request ensuring tests pass.

DataValidation includes extensive unit and feature tests for reliability.

```
composer test
```

Report issues or suggest features on the [GitHub repository](https://github.com/yorcreative/data-validation).

License
-------

[](#license)

DataValidation is licensed under the MIT License. See the [LICENSE](https://github.com/yorcreative/data-validation/blob/main/LICENSE) file for details.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance72

Regular maintenance activity

Popularity13

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 66.7% 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

Unknown

Total

1

Last Release

341d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/51f87d3b079a2d52ebbc2c1b71c65fe3d29717a0122436ef17f55e687ccaa1f4?d=identicon)[yordadev](/maintainers/yordadev)

---

Top Contributors

[![yordadev](https://avatars.githubusercontent.com/u/28032848?v=4)](https://github.com/yordadev "yordadev (2 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

apibenchmarkscustom-rulesdata-validationenterpriseextensiblehigh-performancelightweightmemory-efficientnested-datano-dependenciesopen-sourcepsr-12psr-4securitytest-coveragevalidationvalidatorwildcardphptestingapivalidatorvalidationsecurityextensiblelightweightenterprisePSR-4custom-ruleshigh-performanceno-dependenciesopen-sourcepsr-12data processingdata validationmemory-efficientwildcardbenchmarksnested-data

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

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

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

###  Alternatives

[osteel/openapi-httpfoundation-testing

Validate HttpFoundation requests and responses against OpenAPI (3+) definitions

1201.9M6](/packages/osteel-openapi-httpfoundation-testing)

PHPackages © 2026

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