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

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

hejunjie/schema-validator
=========================

一个简单且可扩展的 PHP 参数验证库，支持规则式定义与自定义扩展，适用于任何结构化数据校验场景 | A simple and extensible PHP parameter validation library, supporting rule-based definitions and custom extensions, suitable for any structured data verification scenarios

v1.0.1(9mo ago)22MITPHPPHP &gt;=8.1

Since Aug 7Pushed 6mo agoCompare

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

READMEChangelog (1)DependenciesVersions (3)Used By (0)

hejunjie/schema-validator
=========================

[](#hejunjieschema-validator)

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

A simple and extensible PHP parameter validation library, supporting rule-based definitions and custom extensions, suitable for any structured data verification scenarios

**This project has been parsed by Zread. If you need a quick overview of the project, you can click here to view it：[Understand this project](https://zread.ai/zxc7563598/php-schema-validator)**

---

📦 Installation method
---------------------

[](#-installation-method)

Install using Composer：

```
composer require hejunjie/schema-validator
```

---

🚀 Usage
-------

[](#-usage)

Support multiple rule definitions + throw exceptions + custom extensions：

```
use Hejunjie\SchemaValidator\Validator;
use Hejunjie\SchemaValidator\Exceptions\ValidationException;

$data = [
    'name'   => '张三',
    'age'    => 28,
    'email'  => 'invalid-email',
];

// Custom extension. If true is returned, the rule passes; otherwise, it is considered as failing
Validator::extend('is_zh', function ($field, $value, $params = null) {
    if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $value)) {
        return true;
    }
});

try {
    Validator::validate($data, [
        'name'  => ['is_zh', 'string', 'minLength:2'],
        'age'   => ['integer', 'between:18,60'],
        'email' => ['required', 'email'],
    ]);
    echo "Verified by ✅";
} catch (ValidationException $e) {
    echo "Validation failed ❌" . PHP_EOL;
    print_r($e->getErrors());
}

// Return the fields and rules indicating whether it is passed or failed:
// Validation failed ❌
// Array
// (
//     [email] => Array
//         (
//             [0] => email
//         )

// )
```

---

✅ Default support rule
----------------------

[](#-default-support-rule)

The following rules are already supported in a built-in manner and are implemented as independent classes, allowing for free extension or replacement：

### Type class

[](#type-class)

Rule NameFunction DescriptionParameter FormatExample Usage`StringRule`Verify whether it is a string`string``['param' => ['string']]``IntegerRule`Verify whether it is an integer`integer``['param' => ['integer']]``BooleanRule`Verify whether it is a boolean value (true/false or 0/1)`boolean``['param' => ['boolean']]``ArrayRule`Verify whether it is an array`array``['param' => ['array']]``ObjectRule`Verify whether it is an object`object``['param' => ['object']]``FloatRule`Verify whether it is a floating-point number`float``['param' => ['float']]``NumericRule`Verify whether it is a number (including integer, floating-point string, etc.)`numeric``['param' => ['numeric']]`---

### Compare class

[](#compare-class)

Rule NameFunction DescriptionParameter FormatExample Usage`MinRule`The numerical value or string length cannot be less than the specified value`min``['param' => ['min:2']]``MaxRule`The size of numbers or the length of strings are not allowed to exceed the specified value`max``['param' => ['max:2']]``BetweenRule`The size of a number or the length of a string must fall within the specified minimum and maximum values`between``['param' => ['between:18,60']]``LengthRule`The length of the string must be equal to the specified value`length``['param' => ['length:10']]``MinLengthRule`The length of the string is not allowed to exceed the specified value`min_length``['param' => ['min_length:2']]``MaxLengthRule`The length of the string cannot be less than the specified value`max_length``['param' => ['max_length:20']]``GtRule`The number must be greater than the specified value`gt``['param' => ['gt:2']]``LtRule`The number must be less than the specified value`lt``['param' => ['lt:2']]``GteRule`The number must be greater than or equal to the specified value`gte``['param' => ['gte:2']]``LteRule`The number must be less than or equal to the specified value`lte``['param' => ['lte:2']]`---

### Format class

[](#format-class)

Rule NameFunction DescriptionParameter FormatExample Usage`EmailRule`The content must be in email format`email``['param' => ['email']]``MobileRule`The content must be in the format of a mainland China mobile phone number`mobile``['param' => ['mobile']]``UrlRule`The content must be a URL`url``['param' => ['url']]``IpRule`The content must be a valid IP address (IPv4 or IPv6)`ip``['param' => ['ip']]``JsonRule`The content must be a valid JSON string`json``['param' => ['json']]``AlphaRule`The content can only contain letters`alpha``['param' => ['alpha']]``AlphaNumRule`The content can only contain letters and numbers`alpha_num``['param' => ['alpha_num']]``AlphaDashRule`The content can only contain letters, numbers, dashes, and underscores`alpha_dash``['param' => ['alpha_dash']]`---

### Boolean class

[](#boolean-class)

Rule NameFunction DescriptionParameter FormatExample Usage`RequiredRule`The content must exist and not be empty`required``['param' => ['required']]``AcceptedRule`The content can only be "yes", "on", "1", or "true"`accepted``['param' => ['accepted']]``DeclinedRule`The content can only be "no", "off", "0", or "false"`declined``['param' => ['declined']]`---

### Custom class

[](#custom-class)

Rule NameFunction DescriptionParameter FormatExample Usage`StartsWithRule`The content must start with the specified string`starts_with``['param' => ['starts_with']]``EndsWithRule`The content must end with the specified string`ends_with``['param' => ['ends_with']]``ContainsRule`The content must contain the specified string`contains``['param' => ['contains']]`> The error message is returned as an array of rule names, and the prompt text can be customized

---

🧩 Purpose &amp; Original Intent
-------------------------------

[](#-purpose--original-intent)

In daily development, we often need to perform structured validation on incoming data, but many existing libraries are either bulky, rely on frameworks, or are not flexible in terms of extension (such as Laravel Validator).

The goal of this library is to:

- ✅ Zero dependencies, suitable for any PHP project
- ✅ Validation for structured arrays
- ✅ Each rule is encapsulated independently, facilitating customization and expansion
- ✅ More suitable for field prompts and error handling in the Chinese context

If you need a simple, clear, and rule-controlled data verification tool, it may be just right for you.

---

🙌 Welcome to contribute
-----------------------

[](#-welcome-to-contribute)

Welcome to raise issues, submit pull requests, or directly fork for use!

If you have other commonly used validation rules, feel free to add them, even if it's just a line of regular expression.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance63

Regular maintenance activity

Popularity5

Limited adoption so far

Community6

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

Total

2

Last Release

280d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5b65d4b40ae456172fb38f63f84bf737ac88031484b1f228b1cc8d71baa80adf?d=identicon)[苏青安](/maintainers/%E8%8B%8F%E9%9D%92%E5%AE%89)

---

Top Contributors

[![zxc7563598](https://avatars.githubusercontent.com/u/46590942?v=4)](https://github.com/zxc7563598 "zxc7563598 (7 commits)")

---

Tags

custom-rulesdata-validationinput-validationphpphp-libraryschema-validationvalidation

### Embed Badge

![Health badge](/badges/hejunjie-schema-validator/health.svg)

```
[![Health](https://phpackages.com/badges/hejunjie-schema-validator/health.svg)](https://phpackages.com/packages/hejunjie-schema-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)[nette/forms

📝 Nette Forms: generating, validating and processing secure forms in PHP. Handy API, fully customizable, server &amp; client side validation and mature design.

54013.2M450](/packages/nette-forms)[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)

PHPackages © 2026

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