PHPackages                             kris-ro/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. kris-ro/validator

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

kris-ro/validator
=================

PHP chainable multi-rule validator for data and POST forms

v1.0.9(1y ago)0211MITPHPPHP 8.\*

Since Aug 25Pushed 1y ago1 watchersCompare

[ Source](https://github.com/kris-ro/validator)[ Packagist](https://packagist.org/packages/kris-ro/validator)[ RSS](/packages/kris-ro-validator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (11)Used By (1)

PHP Validator
=============

[](#php-validator)

Simple class for validating data and POST forms

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

[](#installation)

Use composer to install *Validator*.

```
composer require kris-ro/validator
```

Usage
-----

[](#usage)

```
require YOUR_PATH . '/vendor/autoload.php';

use KrisRo\Validator\Validator;

$validator = new Validator();

# chaining validators
$result = $validator
            ->value('99z9-d_')
            ->addValidationRule('is_string')
            ->addValidationRule('alphanumeric')
            ->process(); # false; only letters and numbers allowed
```

### Magic calls

[](#magic-calls)

```
# the above can be also called as :

$validator = new Validator();
$result = $validator->alphanumeric('99z9-d_'); # false; only letters and numbers allowed

# other validation rules with magic call
(new Validator())->positiveInteger(99999); # true
(new Validator())->positiveInteger('9999s9'); # false
(new Validator())->notEmptyOneLineString('def54%'); # true
(new Validator())->notEmptyOneLineString(''); # false
```

All rules in `$validationRules` in `src/Validator.php` can be called magically as long as they are not PHP reserved words.

### Using a callback class

[](#using-a-callback-class)

```
$validator = new Validator();
$result = $validator
            ->value(999)
            ->addValidationRule([new YourValidationClass(), 'YourMethod'])
            ->process(); # boolean

# callback with static method
$result = $validator
            ->value(999)
            ->addValidationRule(['YourValidationClass', 'YourStaticMethod'])
            ->process(); # boolean
```

### Add a validation regular expression dynamically.

[](#add-a-validation-regular-expression-dynamically)

```
$validator = new Validator();
$result = $validator
            ->createRegexRule('alphanumeric', '/^[a-z0-9\-_]+$/i')
            ->value('abc_-9')
            ->addValidationRule('alphanumeric')
            ->process(); # true

# In constructor
$validator = new Validator(['alphanumeric' => '/^[a-z0-9\-_]+$/i']);
$result = $validator
            ->value('abc_-9')
            ->addValidationRule('alphanumeric')
            ->process(); # true
```

### Validate date

[](#validate-date)

```
$validator = new Validator();
$result = $validator
            ->setDateFormat('m-d-Y')
            ->value('2000-12-12')
            ->addValidationRule('isValidDate') # method of the [KrisRo\Validator\Validator] class
            ->process(); # false, wrong date format
```

### Validate string length

[](#validate-string-length)

```
(new Validator())->value('xx')->minLength(3); # false
(new Validator())->minLength(3, 'xx'); # false

(new Validator())->value('xxx')->maxLength(3); # true
(new Validator())->maxLength(3, 'xxxx'); # false

# chained validators
(new Validator())
            ->value('#Pwd123')
            ->addValidationRule('is_string')
            ->addValidationRule(['minLength', 8])
            ->process(); # false

# in forms
$_POST = [
  'id' => 'DF-999 859',
];

$postValidator = new Validator();

$validationResult = $postValidator
  ->addPostValidationMessages([
    'id' => 'Invalid ID',
  ])
  ->addPostValidationRules([
    'id' => ['notEmptyOneLineString', ['minLength', 5], ['isLength', 10], ['maxLength', 15]],
  ])
  ->processPost(); # true
```

### Validate numerical limits

[](#validate-numerical-limits)

```
(new Validator())->value(10)->smallerThan(9.89); # false
(new Validator())->smallerThan(9.89, 10); # false

(new Validator())->value(1.05)->greaterThan(99.2); # false
(new Validator())->greaterThan(99.2, 1.05); # false

(new Validator())->value(101.05)->between(99.2, 201); # true
(new Validator())->between(99.2, 201, 101.05); # true

# in forms
$_POST = [
  'id' => 'DF-999',
  'int_value' => '999',
  'between_value' => '100',
];

$postValidator = new Validator();

$validationResult = $postValidator
  ->addPostValidationMessages([
    'id' => 'Invalid ID',
    'int_value' => 'Invalid Positive Integer',
    'between_value' => 'Invalid Between Values',
  ])
  ->addPostValidationRules([
    'id' => ['notEmptyOneLineString'],
    'int_value' => ['positiveInteger', ['greaterThan', 'limit' => 99]],
    'between_value' => ['positiveInteger', ['between', 'lowerLimit' => 99, 'upperLimit' => 101]],
  ])
  ->processPost(); # true
```

### Validate email

[](#validate-email)

```
(new Validator())->email('some-email@domain.tld'); # true
(new Validator())->value('some-email@domain.tld')->addValidationRule('is_string')->addValidationRule('email')->process(); # true

(new Validator())->isValidEmail(Validator::EMAIL_VALIDATOR_PHP, 'some-email@domain.tld'); # true
(new Validator())->isValidEmail(Validator::EMAIL_VALIDATOR_REGEXP, 'some-email@domain.tld'); # true
(new Validator())->isValidEmail(Validator::EMAIL_VALIDATOR_REGEXP, 'much.”more\ unusual”@example.com'); # false
(new Validator())->isValidEmail(Validator::EMAIL_VALIDATOR_SIMPLIFIED, 'some-email@domain.tld'); # true - checks if there is a @ character

# in forms
$_POST = [
  'email' => 'much.”more\ unusual”@example.com',
];

$postValidator = new Validator();
$validationResult = $postValidator
  ->addPostValidationMessages([
    'email' => 'Invalid Email Address',
  ])
  ->addPostValidationRules([
    'email' => [['isValidEmail', 'mode' => Validator::EMAIL_VALIDATOR_REGEXP]],
  ])
  ->processPost(); # false

print_r($postValidator->getPostValidationMessages()); # should be ['email' => 'Invalid Email Address']
```

### Validate password strength

[](#validate-password-strength)

```
# by regexp (requires at least 8 letters - including CAPITAL, numbers and special chars)
(new Validator())->strongPassword('password'); # false

# in forms
$_POST = [
  'password' => '#Password123',
];

(new Validator())
  ->addPostValidationMessages([
    'password' => 'Password To Week',
  ])
  ->addPostValidationRules([
    'password' => ['strongPassword'],
  ])
  ->processPost(); # true

# if you wanna punish your users,
# this (on top of strongPassword rule) will fail any password that
# has a same consecutive char more than twice
# or has the same char more than third of the total character count

(new Validator())->paranoiaStrong('#Passrs1') # fails: to many s

# in forms
$_POST = [
  'password' => '#Password123',
];

$postValidator = new Validator();

$validationResult = $postValidator
  ->addPostValidationMessages([
    'password' => 'Password To Week',
  ])
  ->addPostValidationRules([
    'password' => [['minLength', 10], 'paranoiaStrongPassword'],
  ])
  ->processPost(); # true

# using cracklib-runtime library if available
# before using this you need to check if cracklib-runtime library and proc_open function are available

$checker = new CracklibCheck();
(new Validator())->value('Password123')->addValidationRule(['minLength', 6])->addValidationRule([$checker, 'testPassword'])->process(); # false
print_r($checker->getResponseMessage());

# in forms
$_POST = [
  'password' => '#Password123',
];

$checker = new CracklibCheck();
$postValidator = new Validator();

$validationResult = $postValidator
  ->addPostValidationMessages([
    'password' => 'Password To Week',
  ])
  ->addPostValidationRules([
    'password' => [['minLength', 8], [$checker, 'testPassword']],
  ])
  ->processPost(); # true
print_r($checker->getResponseMessage());
```

### Validate POST forms with recursive data

[](#validate-post-forms-with-recursive-data)

```
$_POST = [
  'multiple_values' => ['997', '786', '665'], # will validate values recursively
  'id' => 'DF-999',
];

$postValidator = new Validator();

$validationResult = $postValidator
  ->addPostValidationMessages([
    'id' => 'Invalid ID',
    'multiple_values' => 'Invalid Multiple Values',
  ])
  ->addPostValidationRules([
    'id' => ['notEmptyOneLineString'],
    'multiple_values' => ['positiveInteger'],
  ])
  ->processPost(); # boolean

# Get error messages indexed by the field name
$postValidator->getPostValidationMessages();

# Get validated data, returns array indexed by the field name
$postValidator->getPost();
```

### Validate POST forms with optional data

[](#validate-post-forms-with-optional-data)

```
$_POST = [
  'multiple_values' => [], # will validate optional values
  'id' => 'DF-999',
];

$postValidator = new Validator();

$validationResult = $postValidator
  ->addPostValidationMessages([
    'id' => 'Invalid ID',
    'multiple_values' => 'Invalid Multiple Values',
  ])
  ->addPostValidationRules([
    'id' => ['notEmptyOneLineString'],
    'multiple_values' => ['positiveInteger', 'isOptional'],
  ])
  ->processPost(); # boolean

# Get error messages indexed by the field name
$postValidator->getPostValidationMessages();

# Get validated data, returns array indexed by the field name
$postValidator->getPost();
```

Inheritance
-----------

[](#inheritance)

This class can be extended and overwritten. Almost all methods and properties are public or protected.

You can also extend `KrisRo\Validator\Validator` and update the content of the protected property `validationRules`.

If you need a custom rule use a callback class or extend `KrisRo\Validator\Validator`, create your own validation method in the new class and use the method's name as a validation rule (similar to `isValidDate`).

License
-------

[](#license)

[MIT](https://choosealicense.com/licenses/mit/)

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity46

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 ~4 days

Total

10

Last Release

589d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/37bd75c9e8017bb2ffd7fc58e0e9b9aea5f335df3d2d7ca84805fd6436a1ace4?d=identicon)[kris-ro](/maintainers/kris-ro)

---

Top Contributors

[![kris-ro](https://avatars.githubusercontent.com/u/56273996?v=4)](https://github.com/kris-ro "kris-ro (17 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kris-ro-validator/health.svg)

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

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)[crazybooot/base64-validation

Laravel validators for base64 encoded files

1341.9M8](/packages/crazybooot-base64-validation)

PHPackages © 2026

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