programmatordev/fluent-validator
Composer 安装命令:
composer require programmatordev/fluent-validator
包简介
A Symfony Validator wrapper that enables fluent-style validation for raw values, offering an easy-to-use and intuitive API to validate user input or other data in a concise and readable manner.
关键字:
README 文档
README
A Symfony Validator wrapper that enables fluent-style validation for raw values, offering an easy-to-use and intuitive API to validate user input or other data in a concise and readable manner.
Note
This library will always (try to) be in sync with the latest Symfony Validator version.
Features
- 🌊 Fluent-style validation: Chain validation methods for better readability and flow.
- 🤘 Constraints autocompletion: Enables IDE autocompletion for available constraints.
- 🔥 Three validation methods: Use
validate,assert, orisValidbased on the context (i.e., collect errors or throw exceptions). - ⚙️ Custom constraints: Integrate custom validation logic with Symfony's Validator system.
- 💬 Translations support: Translate validation error messages into multiple languages.
Table of Contents
Requirements
- PHP 8.4 or higher.
Installation
Install via Composer:
composer require programmatordev/fluent-validator
When to use it
Use Fluent Validator when you want Symfony Validator constraints for raw values without setting up object metadata, attributes, forms, or a larger validation layer. It is useful for small input checks, command arguments, request fragments, webhook payload values, configuration values, and library code.
This package does not replace Symfony Validator. It wraps Symfony Validator and keeps its constraints, violation objects, groups, translations, and custom constraint model.
Usage
Simple usage example:
use ProgrammatorDev\FluentValidator\Validator; // example: validate the user's age to ensure it's between 18 and 60 $errors = Validator::notBlank() ->greaterThanOrEqual(18) ->lessThan(60) ->validate($age); if ($errors->count() > 0) { // handle errors }
Use assert when invalid values should stop the current flow:
use ProgrammatorDev\FluentValidator\Exception\ValidationFailedException; use ProgrammatorDev\FluentValidator\Validator; try { Validator::notBlank()->email()->assert($email, 'email'); } catch (ValidationFailedException $exception) { $message = $exception->getMessage(); // "email: This value is not a valid email address." }
Use isValid when you only need a boolean:
use ProgrammatorDev\FluentValidator\Validator; if (!Validator::url()->isValid($website)) { // handle invalid URL }
Constraint autocompletion is available in IDEs like PhpStorm. The suggested methods are generated from the installed Symfony Validator constraints. The method names match Symfony constraints but with a lowercase first letter:
NotBlank=>notBlankAll=>allPasswordStrength=>passwordStrength- ...and so on.
For all available constraints, check the Constraints section.
For all available methods, check the Methods section.
There is also a section for Custom Constraints and Translations.
Groups
Validation groups work the same way as in Symfony Validator:
use ProgrammatorDev\FluentValidator\Validator; $validator = Validator::notBlank(groups: ['Default']) ->email(groups: ['registration']); $validator->isValid('invalid-email', groups: ['Default']); // true $validator->isValid('invalid-email', groups: ['registration']); // false
Constraints
All available constraints can be found on the Symfony Validator documentation.
For custom constraints, check the Custom Constraints section.
Methods
validate
use Symfony\Component\Validator\Constraints\GroupSequence; validate(mixed $value, ?string $name = null, string|GroupSequence|array|null $groups = null): ConstraintViolationListInterface
Returns a ConstraintViolationList object, acting as an array of errors.
use ProgrammatorDev\FluentValidator\Validator; $errors = Validator::email()->validate('test@email.com'); if ($errors->count() > 0) { foreach ($errors as $error) { $message = $error->getMessage(); // ... } }
assert
use Symfony\Component\Validator\Constraints\GroupSequence; assert(mixed $value, ?string $name = null, string|GroupSequence|array|null $groups = null): void
Throws a ValidationFailedException when validation fails.
use ProgrammatorDev\FluentValidator\Exception\ValidationFailedException; use ProgrammatorDev\FluentValidator\Validator; try { Validator::notBlank()->assert($name); Validator::notBlank()->email()->assert($email); } catch (ValidationFailedException $exception) { // the exception message will always be the first error thrown $message = $exception->getMessage(); // value that failed validation $invalidValue = $exception->getInvalidValue(); // get access to all errors // returns a ConstraintViolationList object like in the validate method $errors = $exception->getViolations(); // ... }
isValid
use Symfony\Component\Validator\Constraints\GroupSequence; isValid(mixed $value, string|GroupSequence|array|null $groups = null): bool
Returns a bool indicating if the value is valid.
use ProgrammatorDev\FluentValidator\Validator; if (!Validator::email()->isValid($email)) { // handle invalid email }
toArray
use Symfony\Component\Validator\Constraint; /** @return Constraint[] */ toArray(): array
Returns an array with all added constraints.
use ProgrammatorDev\FluentValidator\Validator; $constraints = Validator::notBlank()->email()->toArray();
It is useful for Composite constraints (i.e., a constraint that is composed of other constraints)
and keeps the fluent-style validation:
use ProgrammatorDev\FluentValidator\Validator; // validate that the array should have at least one value // and each value should be between 0 and 100 $errors = Validator::count(min: 1) ->all(Validator::range(min: 0, max: 100)->toArray()) ->validate($value);
addNamespace
addNamespace(string $namespace): void
Used to add namespaces for custom constraints.
Check the Custom Constraints section.
setTranslator
use Symfony\Contracts\Translation\TranslatorInterface; setTranslator(?TranslatorInterface $translator): void
Used to add a translator for validation error message translations.
Check the Translations section.
reset
reset(): void
Clears globally registered custom constraint namespaces and translator configuration. Useful when changing global validator configuration in tests, workers, or other long-running PHP processes.
Custom Constraints
If you need a custom constraint, follow the Symfony Validator documentation: Creating Custom Constraints.
Example: Creating a ContainsAlphanumeric Constraint
1. Create a Constraint Class
This class defines the error message and configurable options.
namespace App\Constraint; use Symfony\Component\Validator\Constraint; class ContainsAlphanumeric extends Constraint { // set configurable options }
2. Create the Validator Class
The validator checks if the value complies with the constraint rules.
namespace App\Constraint; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; class ContainsAlphanumericValidator extends ConstraintValidator { public function validate(mixed $value, Constraint $constraint): void { // custom validation logic } }
3. Register the Constraint Namespace
Register the namespace where the custom constraints will be located in your project.
use ProgrammatorDev\FluentValidator\Validator; Validator::addNamespace('App\Constraint'); Validator::notBlank()->containsAlphanumeric()->isValid('!'); // false Validator::notBlank()->containsAlphanumeric()->isValid('v4l1d'); // true
You can have multiple constraints in the same namespace or have multiple namespaces.
Note
Custom constraints will not be suggested in IDE autocompletion.
Translations
Set a global translator to handle error message translations.
use ProgrammatorDev\FluentValidator\Translator\Translator; // set translator to Portuguese (Portugal) locale Validator::setTranslator(new Translator('pt')); // now all error messages will be in Portuguese Validator::notBlank()->validate('');
To add your own translations, you can integrate a custom translator.
Contributing
Any form of contribution to improve this library (including requests) will be welcome and appreciated. Make sure to open a pull request or issue.
License
This project is licensed under the MIT license. Please see the LICENSE file distributed with this source code for further information regarding copyright and licensing.
programmatordev/fluent-validator 适用场景与选型建议
programmatordev/fluent-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 03 月 13 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「validator」 「validation」 「php-validation」 「php-validator」 「php8」 「symfony-validator」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 programmatordev/fluent-validator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 programmatordev/fluent-validator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 programmatordev/fluent-validator 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Runn Me! Validation and Sanitization Library
Extension for Opis JSON Schema
WordPress Validation and Sanitization Library
Adds request-parameter validation to the SLIM 3.x PHP framework
A jQuery augmented PHP library for creating and validating HTML forms
A simple validation package in PHP.
统计信息
- 总下载量: 2
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 17
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-03-13