定制 lemmon/validator 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

lemmon/validator

最新稳定版本:v0.15.0

Composer 安装命令:

composer require lemmon/validator

包简介

A lightweight, fluent validation library for PHP.

README 文档

README

CI Latest Stable Version 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

composer require lemmon/validator

Requirements: PHP 8.3 or higher

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

  • 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
  • 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

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

Getting Started

Validation Guides

API Reference

Examples

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

We welcome contributions! Please see our Contributing Guide for details.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Links

统计信息

  • 总下载量: 412
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-09-05

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固