PHPackages                             simplecomplex/validate - 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. simplecomplex/validate

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

simplecomplex/validate
======================

Validate shallowly and recursively (elements of object/array).

2.5.1(6y ago)12752MITPHPPHP &gt;=7.0

Since Jul 12Pushed 5y ago2 watchersCompare

[ Source](https://github.com/simplecomplex/php-validate)[ Packagist](https://packagist.org/packages/simplecomplex/validate)[ Docs](https://github.com/simplecomplex/php-validate)[ RSS](/packages/simplecomplex-validate/feed)WikiDiscussions master Synced 4d ago

READMEChangelogDependencies (1)Versions (26)Used By (2)

Validate
--------

[](#validate)

Validate almost any kind of PHP data structure.

#### Simple shallow validation

[](#simple-shallow-validation)

Test a variable against one of `Validate`s 60+ rule methods

- is it of a particular type or class?
- does it's value match a pattern?
- is it emptyish?
- a container (array|object|traversable)?
- a numerically indexed array?

#### Test against a set of rules

[](#test-against-a-set-of-rules)

A validation rule set is a list of rules (`Validate` methods)
– in effect you can combine all the above questions into a single questions.

You can also declare that "well if it *isn't* an \[object|string|whatever\], then null|false|0 will do just fine".

#### Validate objects/arrays recursively

[](#validate-objectsarrays-recursively)

Validation rule sets can be nested – indefinitely.
`$validate->challenge($subject, $ruleSet)` traverses the subject according to the rule set (+ descendant rule sets),
and checks that the subject at any level/position accords with the rules at that level/position.

#### Record reason(s) for validation failure

[](#record-reasons-for-validation-failure)

`$validate->challengeRecording($subject, $ruleSet)` memorizes all wrongdoings along the way,
and returns a list of violations (including where detected, and what was wrong).

#### Example of use

[](#example-of-use)

[SimpleComplex Http](https://github.com/simplecomplex/php-http) uses validation rule sets to check the body of HTTP (REST) responses.
Rule sets are defined in JSON (readable and portable), and cached as PHP `ValidationRuleSet`s (using [SimpleComplex Cache](https://github.com/simplecomplex/php-cache)).

### Non-rule flags

[](#non-rule-flags)

Multi-dimensional object/array rule sets support a little more than proper validation rules.

- **optional**: the bucket is allowed to be missing
- **allowNull**: the value is allowed to be null
- **alternativeEnum**: list of alternative (scalar|null) values that should make a subject pass,
    even though another rule is violated
- **tableElements**: the subject (an object|array) must contain these keys,
    and for every key there's a sub rule set
- **listItems**: the subject (an object|array) must be a list consisting of a number of buckets,
    which all have the same type/pattern/structure

`alternativeEnum` is great for defining "the bucket must be object or null".

`tableElements` and `listItems` are allowed to co-exist.
Relevant if you have a – kind of malformed – object that may contain list items as well as non-list elements.
Data originating from XML may easily have that structure (XML stinks ;-)

#### tableElements sub flags

[](#tableelements-sub-flags)

- (obj|arr) **rulesByElements** (required): table of rule sets by keys;
    ~ for every key there's a rule set
- (bool) **exclusive**: the object|array must only contain the keys specified by `rulesByElements`
- (arr) **whitelist**: the object|array must – apart from `rulesByElements` – only contain these keys
- (arr) **blacklist**: the object|array must not contain these keys

#### listItems sub flags

[](#listitems-sub-flags)

- (obj|arr) **listItems** (required): a rule set that every list item must comply to
- (int) **minOccur**: there must be at least that many list items
- (int) **maxOccur**: guess what

### Example

[](#example)

```
// We wanna see some bicycles...
class Bicycle
{
    public $wheels = 0;
    public $saddle;
    public $sound = '';
    public $accessories = [];
    public $various;

    public function __construct($wheels, $saddle, $sound, $accessories, $various)
    {
        $this->wheels = $wheels;
        $this->saddle = $saddle;
        $this->sound = $sound;
        $this->accessories = $accessories;
        $this->various = $various;
    }
}

// Not just any kind of bicycles. They must comply to this rule set:
$rule_set = [
    'class' => [
        'Bicycle'
    ],
    'tableElements' => [
        //'exclusive' => true,
        //'whitelist' => ['unspecified_1'],
        //'blacklist' => ['saddle', 'accessories'],
        'rulesByElements' => [
            'wheels' => [
                'integer',
                'range' => [
                    1,
                    3
                ]
            ],
            'saddle' => [
                'integer',
                'alternativeEnum' => [
                    // Wrongly defined as nested; confused by enum which
                    // formally requires to be nested.
                    // But ValidationRuleSet fixes this, as it does with
                    // the opposite for (un-nested) enum.
                    [
                        true,
                    ]
                ]
            ],
            'sound' => [
                'string' => true,
                'enum' => [
                    // Counterintuitive nesting, but formally correct because
                    // the allowed values array is second arg to the enum()
                    // method.
                    // ValidationRuleSet fixes un-nested instance.
                    [
                        'silent',
                        'swooshy',
                        'clattering',
                    ]
                ]
            ],
            'accessories' => [
                'array',
                'tableElements' => [
                    'rulesByElements' => [
                        'luggageCarrier' => [
                            'boolean',
                            'optional'
                        ],
                        'lights' => [
                            'numeric',
                            'optional'
                        ]
                    ]
                ]
            ],
            'various' => [
                'array',
                'optional',
                // allowNull and alternativeEnum with null
                // are two ways of allowing null.
                'allowNull' => true,
                'alternativeEnum' => [
                    null,
                ],
                'listItems' => [
                    'maxOccur' => 5,
                    'itemRules' => [
                        'string',
                        'alternativeEnum' => [
                            // Correctly defined as un-nested array.
                            true,
                            false,
                        ]
                    ]
                ]
            ]
        ]
    ]
];
```

#### Requirements

[](#requirements)

- PHP &gt;=7.0
- [SimpleComplex Utils](https://github.com/simplecomplex/php-utils)

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity68

Established project with proven stability

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

Recently: every ~40 days

Total

16

Last Release

2503d ago

Major Versions

0.9 → 1.02017-09-24

1.0.2 → 2.02018-06-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/cc4dc35e0d2b8e4619ae2fe2d083cb3c64b09127ecb318c3909025fc0aae1e7f?d=identicon)[jacobfriis](/maintainers/jacobfriis)

---

Top Contributors

[![jacobfriis](https://avatars.githubusercontent.com/u/3807905?v=4)](https://github.com/jacobfriis "jacobfriis (136 commits)")

---

Tags

phpphp7psrvalidatevalidationphpvalidate

### Embed Badge

![Health badge](/badges/simplecomplex-validate/health.svg)

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

###  Alternatives

[jlorente/php-credit-cards

A PHP package to perform operations on debit and credit cards like format, validate brand, number and Luhn algorithm. It validates popular brands like Visa, Mastercard, American Express, etc.

44421.2k1](/packages/jlorente-php-credit-cards)[tecactus/reniec-php

RENIEC package for PHP

118.4k](/packages/tecactus-reniec-php)

PHPackages © 2026

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