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

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

lemmon/validator
================

A lightweight, fluent validation library for PHP.

v0.15.0(2mo ago)4481↓28.6%MITPHPPHP ^8.3CI passing

Since Sep 5Pushed 1mo agoCompare

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

READMEChangelogDependencies (17)Versions (18)Used By (0)

Lemmon Validator
================

[](#lemmon-validator)

[![CI](https://github.com/lemmon/validator-php/actions/workflows/ci.yml/badge.svg)](https://github.com/lemmon/validator-php/actions/workflows/ci.yml)[![Latest Stable Version](https://camo.githubusercontent.com/2e5bfe0919c8545956ff41245a87c756a4093205bf2f49a345115f6dd0c521e6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c656d6d6f6e2f76616c696461746f722e737667)](https://packagist.org/packages/lemmon/validator)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)

Note

This library is in active development. The API may change in future versions as we refine and improve the developer experience based on real-world usage and feedback.

Lemmon Validator is a comprehensive, fluent validation and data processing library for PHP that prioritizes developer experience, type safety, and real-world practicality. Inspired by modern validation libraries like Valibot and Zod, it brings a chainable, readable API to PHP for validation, transformation, and sanitization with intelligent error handling and form-safe defaults.

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

[](#installation)

```
composer require lemmon/validator
```

**Requirements:** PHP 8.3 or higher

About
-----

[](#about)

**Philosophy: "Simple and Minimal with Extensibility Over Reinvention"**

Rather than reimplementing every possible transformation or validation rule, Lemmon Validator provides a solid foundation with generic `transform()` and `pipe()` methods that integrate seamlessly with PHP's ecosystem. Need complex string transformations? Plug in Laravel's `Str` class through our transformation system. Need advanced array operations? Connect Laravel Collections via our fluent API. The library focuses on what it does best: type-safe validation with excellent developer experience, while enabling you to leverage the entire PHP ecosystem.

**Key Design Principles:**

- **Type-Safe Architecture**: Modern PHP 8.1+ enums provide IDE autocomplete, refactoring safety, and eliminate magic strings throughout the codebase
- **Smart Null Handling**: Validations skip `null` unless `required()`. `transform()` and `pipe()` skip `null` by default for type safety. Use `transform($fn, skipNull: false)` to process null values.
- **Form Safety First**: Empty strings coerce to `null` (not dangerous `0`/`false`) to prevent real-world issues like accidental zero bank balances
- **Fluent API with Execution Order Guarantee**: Validation rules read like natural language and execute in the exact order written -- `Validator::isString()->pipe('trim')->nullifyEmpty()->required()`
- **Last-Resort Default**: `default()` is a flag applied after the pipeline -- fills in null only as a last resort, before `required()` enforces presence
- **Fail-Fast Per Field**: Each validator stops at the first failing rule, while schema validation still aggregates errors across fields
- **API-Friendly Error Format**: Flattened errors with field paths (`'_root'` for root-level, dot notation for nested) perfect for frontend consumption
- **Type-Aware Transformations**: Intelligent transformation system that maintains type context and handles coercion automatically
- **Extensible Architecture**: Generic transformation methods work with any PHP callable or external library
- **Strict Typing**: All files use `declare(strict_types=1);`, keeping internal type hints strict; opt into `coerce()` when you need form-friendly conversions.

Features
--------

[](#features)

- **Type-safe architecture** - PHP 8.1+ enums with IDE autocomplete, refactoring safety, and zero magic strings
- **Smart null handling** - validations skip `null` unless `required()`, `transform()`/`pipe()`/`nullifyEmpty()` skip `null` by default
- **Type-safe validation** for strings, integers, floats, arrays, and objects
- **Fluent, chainable API** with guaranteed execution order -- methods execute exactly as written in the chain
- **Schema-level error aggregation** with fail-fast behavior per field for clear, early feedback
- **Structured errors** - `getStructuredErrors()` returns `ValidationError` objects with a stable `code` (see `ValidationCode`), dotted `path`, `message`, and `params` for programmatic handling and i18n; match on codes rather than message text
- **API-friendly flattened errors** with field paths for easy frontend integration (`getFlattenedErrors()`, `ValidationException::flattenErrors()`)
- **Intuitive custom validation** with `satisfies()` method and optional error messages
- **Single-value validation** with `const()` for exact value matching (available on all validators)
- **PHP enum validation** with `enum()` for `BackedEnum` (backed values) and `UnitEnum` (case instances or string case names) (available on all validators)
- **Logical combinators** (`Validator::allOf()`, `Validator::anyOf()`, `Validator::not()`) for complex validation logic
- **Form-safe coercion** - empty strings become `null` (not dangerous `0`/`false`) for real-world safety
- **Accurate schema validation** - results only include provided fields and fields with defaults (no unexpected properties)
- **Universal transformations** (`transform()`, `pipe()`) for post-validation data processing
- **Null-safe operations** with `nullifyEmpty()` method for consistent empty value handling

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

[](#quick-start)

All runtime classes live under the `Lemmon\Validator` namespace.

```
use Lemmon\Validator\Validator;

// Simple validation with form-safe coercion
$email = Validator::isString()
    ->email()
    ->nullifyEmpty() // Empty strings become null (form-safe)
    ->validate('user@example.com');

// Schema validation with custom logic
$userSchema = Validator::isAssociative([
    'name' => Validator::isString()->required(),
    'age' => Validator::isInt()->min(18)->coerce(),
    'email' => Validator::isString()->email()->nullifyEmpty(),
    'password' => Validator::isString()->satisfies(fn($v) => strlen($v) >= 8, 'Password too short')
]);

// Tuple-based validation (no exceptions)
[$valid, $user, $errors] = $userSchema->tryValidate($input);
if (!$valid) {
    $flattened = \Lemmon\Validator\ValidationException::flattenErrors($errors);
    // Returns: [['path' => 'name', 'message' => 'Value is required'], ...]
}

// Exception-based validation
try {
    $user = $userSchema->validate($input);
} catch (\Lemmon\Validator\ValidationException $e) {
    $flattened = $e->getFlattenedErrors();
    // Returns: [['path' => 'name', 'message' => 'Value is required'], ...]
}
```

Documentation
-------------

[](#documentation)

### Getting Started

[](#getting-started)

- [Installation &amp; Setup](docs/getting-started/installation.md)
- [Basic Usage](docs/getting-started/basic-usage.md)
- [Core Concepts](docs/getting-started/core-concepts.md)

### Validation Guides

[](#validation-guides)

- [String Validation](docs/guides/string-validation.md) -- Email, URL, patterns, length constraints
- [Numeric Validation](docs/guides/numeric-validation.md) -- Integers, floats, ranges, constraints
- [Array Validation](docs/guides/array-validation.md) -- Indexed arrays and item validation
- [Object &amp; Schema Validation](docs/guides/object-validation.md) -- Complex nested structures
- [Custom Validation](docs/guides/custom-validation.md) -- User-defined functions and business logic
- [Error Handling](docs/guides/error-handling.md) -- Working with validation errors

### API Reference

[](#api-reference)

- [Validator Factory](docs/api-reference/validator-factory.md)

### Examples

[](#examples)

- [Form Validation](docs/examples/form-validation.md)

### For AI Agents

[](#for-ai-agents)

- **`llms.txt`** - Complete technical specification with full API signatures, method parameters, and core concepts. Download this file and provide it to your AI agent for accurate code generation and assistance with the library.

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

[](#contributing)

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Links
-----

[](#links)

- [Packagist](https://packagist.org/packages/lemmon/validator)
- [GitHub Repository](https://github.com/lemmon/validator-php)
- [Issue Tracker](https://github.com/lemmon/validator-php/issues)
- [Changelog](CHANGELOG.md)

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance89

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

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

Recently: every ~25 days

Total

17

Last Release

80d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/69d2fc0d66f2e8e99490f3781a67d2af0d6ca9cb3e48db4a6199336344d4310c?d=identicon)[lemmon](/maintainers/lemmon)

---

Top Contributors

[![lemmon](https://avatars.githubusercontent.com/u/251591?v=4)](https://github.com/lemmon "lemmon (105 commits)")

---

Tags

data-validationlibraryphpschema-validationtype-coercionvalidationvalidatorschemavalidatorvalidationzodvalibot

###  Code Quality

TestsPest

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[respect/validation

The most awesome validation engine ever created for PHP

6.0k39.9M415](/packages/respect-validation)[opis/json-schema

Json Schema Validator for PHP

65243.6M302](/packages/opis-json-schema)[vlucas/valitron

Simple, elegant, stand-alone validation library with NO dependencies

1.7k4.6M141](/packages/vlucas-valitron)[intervention/validation

Additional validation rules for the Laravel framework

6827.2M20](/packages/intervention-validation)[laravel-validation-rules/credit-card

Validate credit card number, expiration date, cvc

2462.4M7](/packages/laravel-validation-rules-credit-card)[particle/validator

Flexible and highly usable validation library with no dependencies.

2612.1M10](/packages/particle-validator)

PHPackages © 2026

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