PHPackages                             blakvghost/php-validator - 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. blakvghost/php-validator

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

blakvghost/php-validator
========================

PHPValidator is a modern PHP library for data validation in your PHP applications. It provides a flexible and extensible way to validate data using predefined rules or by creating custom validation rules.

v2.3.1(7mo ago)2625.8k↑36.7%4[4 issues](https://github.com/BlakvGhost/PHPValidator/issues)[2 PRs](https://github.com/BlakvGhost/PHPValidator/pulls)3MITPHPPHP &gt;=8.1CI passing

Since Nov 16Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/BlakvGhost/PHPValidator)[ Packagist](https://packagist.org/packages/blakvghost/php-validator)[ RSS](/packages/blakvghost-php-validator/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (10)Dependencies (1)Versions (16)Used By (3)

[![logo PHPValidator for Black Background](docs/logo-no-background.svg)](docs/logo-no-background.svg)

[![logo PHPValidator for White Background](docs/logo-with-background.png)](docs/logo-with-background.png)[![Packagist Version (custom server)](https://camo.githubusercontent.com/77f0010ed909bf836db386d02c1a3ac6bc475deae9956c9ba56987d7517c7e9d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f426c616b7647686f73742f7068702d76616c696461746f723f6c6162656c3d737461626c65)](https://camo.githubusercontent.com/77f0010ed909bf836db386d02c1a3ac6bc475deae9956c9ba56987d7517c7e9d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f426c616b7647686f73742f7068702d76616c696461746f723f6c6162656c3d737461626c65)[![Packagist Version (custom server)](https://camo.githubusercontent.com/61b37e84a246b26997cc17c54f08eeb33ddf52784db5ae3f9c70e130a0515157/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f426c616b7647686f73742f7068702d76616c696461746f723f6c6162656c3d4c6963656e6365)](https://camo.githubusercontent.com/61b37e84a246b26997cc17c54f08eeb33ddf52784db5ae3f9c70e130a0515157/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f426c616b7647686f73742f7068702d76616c696461746f723f6c6162656c3d4c6963656e6365)[![Packagist Version (custom server)](https://camo.githubusercontent.com/6fe5bbd4d2c32df4cf43a3faea163ad1d3b3a470161061f8a8f3ff47803732e9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f426c616b7647686f73742f7068702d76616c696461746f723f6c6162656c3d646f776e6c6f6164)](https://camo.githubusercontent.com/6fe5bbd4d2c32df4cf43a3faea163ad1d3b3a470161061f8a8f3ff47803732e9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f426c616b7647686f73742f7068702d76616c696461746f723f6c6162656c3d646f776e6c6f6164)

About PHPValidator
------------------

[](#about-phpvalidator)

A modern PHP library for data validation in your applications. PHPValidator provides a flexible and extensible approach to validating data using predefined rules or by creating custom validation rules.

---

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

[](#installation)

Install PHPValidator via Composer:

```
composer require blakvghost/php-validator
```

---

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

[](#quick-start)

```
use BlakvGhost\PHPValidator\Validator;
use BlakvGhost\PHPValidator\ValidatorException;

try {
    $data = [
        'username' => 'BlakvGhost',
        'email' => 'example@example.com',
        'score' => 42,
        'tags' => [
            ['name' => 'php'],
            ['name' => 'validation'],
        ],
        'friend' => [
            'email' => 'test@example.com',
            'profile' => [
                'first_name' => 'Kabirou',
            ],
        ],
    ];

    $validator = new Validator($data, [
        'username' => 'required|string',
        'email' => 'required|email',
        'tags.*.name' => 'required|string',
        'score' => ['required', 'max:200', new CustomRule()],
        'password' => new CustomRule(),
        'friend.profile.first_name' => 'required|string',
    ]);

    if ($validator->isValid()) {
        echo "Validation passed!";
    } else {
        $errors = $validator->getErrors();
        print_r($errors);
    }
} catch (ValidatorException $e) {
    echo "Validation error: " . $e->getMessage();
}
```

---

Customize Messages
------------------

[](#customize-messages)

You can customize error messages or specify the default language:

```
$data = ['username' => 'BlakvGhost'];

$validator = new Validator(
    $data,
    ['username' => 'required|string'],
    [
        'username' => [
            'required' => 'Your username must be present',
            'string' => 'Your username must be a string',
        ],
    ]
);

// Or set the default language
$validator = new Validator($data, $rules, lang: 'en');
```

---

Nested and Wildcard Notation
----------------------------

[](#nested-and-wildcard-notation)

PHPValidator supports dot notation for validating deeply nested fields, as well as wildcard notation (`*`) to apply rules across arrays of data.

### Nested Keys

[](#nested-keys)

Validate nested fields using dot notation:

```
$data = [
    'user' => [
        'profile' => [
            'first_name' => 'Kabirou',
        ]
    ]
];

$rules = [
    'user.profile.first_name' => 'required|string',
];
```

### Wildcard Notation

[](#wildcard-notation)

Use `*` as a wildcard to apply the same rule to all elements of an array:

```
$data = [
    'products' => [
        ['name' => 'Banana'],
        ['name' => 'Apple'],
    ]
];

$rules = [
    'products.*.name' => 'required|string',
];
```

---

Key Features
------------

[](#key-features)

- **Predefined Rules** : A comprehensive set of ready-to-use validation rules (required, string, email, maxLength, etc.)
- **Custom Rules** : Easily create your own validation rules by implementing the `Rule` interface
- **Multilingual Support** : Customize error messages according to your application's language
- **Nested Validation** : Validate complex data structures with dot notation
- **Wildcard Notation** : Apply rules to all elements in an array

---

Predefined Rules
----------------

[](#predefined-rules)

### Basic Validation

[](#basic-validation)

RuleExampleDescription`required``'username' => 'required'`Ensures the field is present in the data`string``'username' => 'string'`Checks if the field is of string type`nullable``'optional_field' => 'nullable'`Allows the field to be null or empty`not_nullable``'optional_field' => 'not_nullable'`The field must not be null or empty### Text Validation

[](#text-validation)

RuleExampleDescription`email``'email' => 'email'`Validates a well-formed email address`alpha``'name' => 'alpha'`Contains only alphabetic characters`numeric``'age' => 'numeric'`Contains only numeric characters`alpha_num``'pseudo' => 'alpha_num'`Contains only alphanumeric characters`lowercase``'username' => 'lowercase'`Contains only lowercase alphabetic characters`uppercase``'username' => 'uppercase'`Contains only uppercase alphabetic characters### Length Validation

[](#length-validation)

RuleExampleDescription`min``'username' => 'min:8'`Minimum length of a string`max``'username' => 'max:25'`Maximum length of a string`size``'string' => 'size:7'`Exact size of a string, integer, array, or file**Size Rule Examples:**

```
[
    'string' => 'size:7',          // strlen(string) == 7
    'integer' => 'size:7',         // integer == 7
    'array' => 'size:7',           // count(array) == 7
    'file' => 'size:512',          // file size (kb) == 512
]
```

### Comparison Validation

[](#comparison-validation)

RuleExampleDescription`in``'role' => 'in:admin,editor,viewer'`Value must be in a predefined list`not_in``'value' => 'not_in:foo,bar'`Value must not be in the specified list`same``'password_confirmation' => 'same:password'`Field value equals another field's value`confirmed``'password_confirmation' => 'confirmed:password'`Field matches another field (for confirmation)### Security Validation

[](#security-validation)

RuleExampleDescription`password``'password' => 'password'`Validates a secure password### File and URL Validation

[](#file-and-url-validation)

RuleExampleDescription`file``'file' => 'file'`Validates that a field is a file upload`url``'website' => 'url'`Validates that a field is a valid URL`active_url``'website' => 'active_url'`Validates that a field is a valid, active URL### Format Validation

[](#format-validation)

RuleExampleDescription`bool``'is_admin' => 'bool'`Validates that a field is a boolean`ip``'client_ip' => 'ip'`Validates that a field is a valid IP address`json``'config' => 'json'`Validates that a field is a valid JSON string### Conditional Validation

[](#conditional-validation)

RuleExampleDescription`accepted``'terms_and_conditions' => 'accepted'`Field is "yes", "on", "1", or true (useful for checkboxes)`accepted_if``'terms_and_conditions' => 'accepted_if:is_adult,true'`Field is accepted if another field equals a value`required_with``'firstname' => 'required_with:lastname'`Field is required if another field is present`not_required_with``'email' => 'not_required_with:phone_number'`Field must not be present if another field is present---

Extract Validated Data
----------------------

[](#extract-validated-data)

The `validated()` method returns only fields that:

- have validation rules
- passed validation successfully

```
$data = [
    'name' => 'John',
    'age' => 30,
    'extra_field' => 'ignored'
];

$validator = new Validator($data, [
    'name' => 'required',
    'age' => 'required',
]);

$validated = $validator->validated();

// Result:
[
    'name' => 'John',
    'age' => 30
]
```

---

Create Custom Rules
-------------------

[](#create-custom-rules)

Beyond predefined rules, you can create your own validation rules by implementing the `Rule` interface.

### Example: CustomPasswordRule.php

[](#example-custompasswordrulephp)

```
namespace YourNameSpace\Rules;

use BlakvGhost\PHPValidator\Contracts\Rule;

class CustomPasswordRule implements Rule
{
    protected $field;

    public function __construct(protected array $parameters = [])
    {
    }

    public function passes(string $field, $value, array $data): bool
    {
        $this->field = $field;
        // Implement your custom validation logic here
        // Example: Check if the password equals confirm_password
        return $value === $data['confirm_password'];
    }

    public function message(): string
    {
        return "Your passwords do not match";
    }
}
```

### Usage in Validator

[](#usage-in-validator)

**Method 1: Use your class directly**

```
use BlakvGhost\PHPValidator\Validator;
use BlakvGhost\PHPValidator\ValidatorException;
use YourNameSpace\CustomPasswordRule;

try {
    $data = [
        'password' => '42',
        'confirm_password' => '142',
    ];

    $validator = new Validator($data, [
        'password' => ['required', new CustomPasswordRule()],
    ]);

    if ($validator->isValid()) {
        echo "Validation passed!";
    } else {
        print_r($validator->getErrors());
    }
} catch (ValidatorException $e) {
    echo "Error: " . $e->getMessage();
}
```

**Method 2: Add to the rules list and use as a native rule**

```
use BlakvGhost\PHPValidator\Validator;
use BlakvGhost\PHPValidator\ValidatorException;
use BlakvGhost\PHPValidator\Mapping\RulesMaped;
use YourNameSpace\CustomPasswordRule;

// Add your rule with an alias and the full namespace
RulesMaped::addRule('c_password', CustomPasswordRule::class);

try {
    $data = [
        'password' => '42',
        'confirm_password' => '142',
    ];

    $validator = new Validator($data, [
        'password' => 'required|c_password',
    ]);

    if ($validator->isValid()) {
        echo "Validation passed!";
    } else {
        print_r($validator->getErrors());
    }
} catch (ValidatorException $e) {
    echo "Error: " . $e->getMessage();
}
```

---

Testing
-------

[](#testing)

PHPValidator is fully tested using [PestPHP](https://pestphp.com/).

Run all tests:

```
composer test
```

Or manually:

```
./vendor/bin/pest
```

Tests are located in the `/tests/Feature` directory and include examples for:

- `nullable` and `not_nullable` rules
- `validated()` behavior
- Nested and wildcard validations

---

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

[](#contributing)

If you would like to contribute to PHPValidator, please follow our [Contribution Guidelines](CONTRIBUTING.md).

---

Author
------

[](#author)

**Kabirou ALASSANE** - [GitHub](https://github.com/BlakvGhost)

---

Support
-------

[](#support)

For questions or assistance with PHPValidator, you can contact me at .

---

License
-------

[](#license)

PHPValidator is open-source software licensed under the MIT license.

###  Health Score

48

—

FairBetter than 93% of packages

Maintenance62

Regular maintenance activity

Popularity38

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.3% 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 ~53 days

Recently: every ~141 days

Total

15

Last Release

211d ago

Major Versions

v1.4.1 → v2.0.02023-12-09

### Community

Maintainers

![](https://www.gravatar.com/avatar/32071894442eb051f8fe93e40d54e3ec7ada5d6c5ac60e75bc200781176c2a86?d=identicon)[BlakvGhost](/maintainers/BlakvGhost)

---

Top Contributors

[![BlakvGhost](https://avatars.githubusercontent.com/u/86885681?v=4)](https://github.com/BlakvGhost "BlakvGhost (151 commits)")[![v1p3r75](https://avatars.githubusercontent.com/u/61166921?v=4)](https://github.com/v1p3r75 "v1p3r75 (15 commits)")[![ollyollyollyltd](https://avatars.githubusercontent.com/u/5054551?v=4)](https://github.com/ollyollyollyltd "ollyollyollyltd (5 commits)")

---

Tags

phpphp-libraryvalidatorphpvalidationPHP Libraryvalidation-rulesdata validationcustom validation

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/blakvghost-php-validator/health.svg)

```
[![Health](https://phpackages.com/badges/blakvghost-php-validator/health.svg)](https://phpackages.com/packages/blakvghost-php-validator)
```

PHPackages © 2026

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