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

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

hongxunpan/validator
====================

Framework-agnostic validator core with extensible DSL keywords and adapter-friendly contracts

0.0.7(2w ago)04MITPHPPHP &gt;=5.6CI passing

Since May 16Pushed 2w agoCompare

[ Source](https://github.com/HongXunPan/php-validator)[ Packagist](https://packagist.org/packages/hongxunpan/validator)[ Docs](https://github.com/HongXunPan/php-validator)[ RSS](/packages/hongxunpan-validator/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (1)Versions (8)Used By (0)

Validator
=========

[](#validator)

[简体中文文档](./README.zh-CN.md)

`hongxunpan/validator` is a framework-agnostic validator core built around three ideas:

- rules are public extension units and execute themselves;
- consumers extend through validator subclass arrays instead of handler/source registries;
- the kernel only orchestrates and pushes execution details into smaller collaborators.

Current Status
--------------

[](#current-status)

This repository is in pre-1.0 development.

For change history, see:

- [CHANGELOG](./CHANGELOG.md)

For contribution workflow, see:

- [Contribution Guide](./CONTRIBUTING.md)

For current performance notes, see:

- [Performance and Benchmark Notes (Chinese)](./docs/%E6%80%A7%E8%83%BD%E4%B8%8E%E5%9F%BA%E5%87%86%E8%AF%B4%E6%98%8E.zh-CN.md)

For richer canonical usage scenarios, see:

- [High-value Canonical Examples](./docs/high-value-canonical-examples.md)

For rule capabilities, planning status, and rejection reasons, see:

- [Rule Capability Matrix](./docs/rule-capability-matrix.md)

If you are evaluating migration from Laravel Validator, Symfony Validator, Respect, Valitron, Rakit, or similar packages, read:

- [Comparison With Other Validator Libraries](./docs/comparison-with-other-validators.md)
- [Migration From Other Validator Libraries](./docs/migration-from-other-validators.md)

Already in place:

- Composer package skeleton;
- PHP `>=5.6` compatibility baseline;
- `RuleInterface + AbstractRule + KEY + of(...) / ofJson(...)` public convention;
- validator subclass extension configuration:
    - `extraRules`
    - `ruleAliases`
    - `ruleMessages`
- canonical core validation pipeline.

Still in progress:

- broader core canonical rule coverage;
- backend adapter integration;
- README examples and release hardening.

Selection Summary
-----------------

[](#selection-summary)

This package is not a full replacement for Laravel Validator or Symfony Validator. It is a low-dependency, framework-agnostic validation and normalization core for array-like input.

Typical reasons to choose it:

- you need a reusable validation core for non-Laravel projects, shared Composer packages, or older PHP runtimes;
- you want custom rules to be the first-class design priority, represented by structured `Rule` classes instead of long-lived callbacks or opaque arrays;
- you need validation, normalization, default value creation, conditional rules, and cross-field dependency reads in one testable pipeline;
- you want the core to stay low-dependency while keeping ORM, HTTP responses, file uploads, and framework-specific behavior in adapter layers.

Typical reasons not to choose it:

- your Laravel project only needs regular form validation, FormRequest, `unique / exists`, or file upload rules;
- your Symfony project is mainly modeled around Entity / DTO / Attribute constraints;
- you need hundreds of built-in rules first, rather than a long-term custom-rule extension surface.

The detailed comparison and migration cost are documented in the two docs linked above. README only keeps this decision-level summary to avoid turning the landing page into a long essay.

Public Extension Model
----------------------

[](#public-extension-model)

Default consumers only need a validator subclass:

```
class DemoValidator extends Validator
{
    protected static $extraRules = array(
        'trimTest' => TrimTestRule::class,
    );

    protected static $ruleAliases = array(
        'trimAlias' => 'trimTest',
    );

    protected static $ruleMessages = array(
        'trimTest' => '$paramName must be trimmed',
    );
}
```

When these maps become large, prefer two paths depending on the use case:

- if you only want to split long static maps out of the validator class, prefer the provider-class constants:
    - `EXTRA_RULES_PROVIDER_CLASS`
    - `RULE_ALIASES_PROVIDER_CLASS`
    - `RULE_MESSAGES_PROVIDER_CLASS`
- only override:
    - `defineExtraRules()`
    - `defineRuleAliases()`
    - `defineRuleMessages()`when you really need inherited merging or dynamic logic.

Rule lookup order is fixed:

1. try the input rule key as a real rule;
2. only when it does not exist, try alias mapping;
3. resolve the final rule class;
4. execute `RuleClass::validate(RuleContext $context)`.

Public DSL Conventions
----------------------

[](#public-dsl-conventions)

- rule strings use `ruleName[:argument]`;
- each rule only splits on the first `:`;
- public keyword classes expose:
    - `KEY`
    - `key()`
    - `of(...)` for raw arguments;
    - `ofJson(...)` for JSON-encoded arguments such as `InRule::ofJson(array('draft', 'published'))`;
- rules that declare JSON literal parameters, such as `in / notIn / startsWith / requiredKeys`, should prefer `ofJson(...)` in PHP code to avoid hand-written escaping;
- use the three-layer builder model for compound arguments and rule chains:
    - `RuleArg`: builds argument fragments only, such as `fieldValue($field, $value)`, `fieldValues($field, $values)`, and `range($min, $max)`;
    - semantic helpers on concrete rule classes: build a single rule token, such as `RequiredIfEqRule::ofFieldValue(...)`, `RequiredIfInRule::ofFieldValues(...)`, and `GteFieldRule::ofField(...)`;
    - `RuleChain::join(...)`: combines rule tokens instead of hand-written `implode('|', ...)` or repeated string concatenation;
- `ofJson(...)` is for rules whose whole argument is JSON; compound arguments such as `requiredIfEq:field,JSON-value` should prefer `ofFieldValue(...)`.

```
use HongXunPan\Validator\Rule\Assert\Common\InRule;
use HongXunPan\Validator\Rule\Condition\NullableIfNotEqRule;
use HongXunPan\Validator\Rule\Condition\RequiredIfEqRule;
use HongXunPan\Validator\Rule\RuleChain;

'status:Status' => 'required|' . InRule::ofJson(array('draft', 'published'));
'source_id:Source ID' => RuleChain::join(array(
    RequiredIfEqRule::ofFieldValue('target_mode', 'activity_checkin_users'),
    NullableIfNotEqRule::ofFieldValue('target_mode', 'activity_checkin_users'),
    'nonNegativeInt',
));
```

Package Layout
--------------

[](#package-layout)

```
src/
  Validator.php
  ValidationKernel.php
  Internal/
  Rule/
  Context/
  Support/
  Result/
  Output/
  Exception/
tests/

```

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

[](#installation)

```
composer require hongxunpan/validator
```

30-second Quick Start
---------------------

[](#30-second-quick-start)

```
