Respect\Validation 3.0
Respect\Validation 3.0 is a major release with breaking changes, improved performance, and new features for more flexible validation. This version requires PHP 8.5+ (up from 8.1+ in 2.x). Update via:
composer require respect/validation:^3.0For detailed migration instructions, see the Migration Guide.
Breaking Changes
- Class and Namespace Renames:
Validatorrenamed toValidatorBuilderRulesnamespace toValidatorsRuleinterface toValidatorFactorytoValidatorFactoryInvalidRuleConstructorExceptiontoInvalidValidatorException.
- Validation Methods:
validate()now returns aResultQueryobject instead of a boolean (useisValid()for boolean checks)check()andassert()now throw a unifiedValidationException(validator-specific exceptions removed;NestedValidationExceptionremoved).
- Removed Validators:
Type(use specific type validators likestringType())Yes/No(usetrueVal()/falseVal())KeyNested(use nestedkey())Age/MinAge/MaxAge(usedateTimeDiff())PrimeNumber/Fibonacci/PerfectSquare/FilterVar/Uploaded(usesatisfies())VideoUrl(no direct replacement).
- Behavior Changes:
Attributereplaced byProperty/PropertyOptional/PropertyExistsKeysplit intoKey/KeyOptional/KeyExistsLengthandSizesignatures changed to use composition (e.g.,length(v::between(5, 10)))Eachstricter (rejects non-iterables likestdClass)- Composite validators (
AllOf, etc.) require at least two validators After(ex-Call) no longer handles callback errorsContains/ContainsAny/In/EndsWith/StartsWithnow strict by defaultUrlvalidates domains/IPs, dropsnewsscheme, addsEmailformailto- New dependencies for some validators (
sokil/php-isocodes,ramsey/uuid).
- Renamed Validators:
CalltoAfterCallbacktoSatisfiesMintoGreaterThanOrEqualMaxtoLessThanOrEqualNullabletoNullOrOptionaltoUndefOrKeyValuetoFactoryNotBlankinverted toBlank(usenot(v::blank()))NotEmptyinverted/renamed toFalsy(usenot(v::falsy()))NoWhitespaceinverted/renamed toSpaced(usenot(v::spaced()))IterableTypetoIterableVal(stricterIterableTypenow exists separately).
- Custom Messages:
setTemplate()andsetName()removed (usetemplated()andnamed()){{name}}placeholder renamed to{{subject}}.
- Factory/Container:
Factoryreplaced by PSR-11 container viaContainerRegistry. - Custom Validators: No longer need separate exception classes
- use
#[Template]attributes on validator classes.
- use
New Features
-
Result-Based Validation:
validate()returns aResultQueryfor detailed error inspection.$result = v::numericVal()->positive()->between(1, 255)->validate($input); $result->hasFailed(); // bool $result->getFullMessage(); // All errors as tree
-
Attribute Validation: Validate object properties via PHP attributes.
class User { #[Validators\Email] public string $email; #[Validators\Between(18, 120)] public int $age; } v::attributes()->assert($user); // Validates all annotated properties
-
ShortCircuit Validation: Stops at first failure for dependent checks.
v::shortCircuit( v::key('countryCode', v::countryCode()), v::factory(fn($input) => v::key('subdivisionCode', v::subdivisionCode($input['countryCode']))) )->assert(['countryCode' => 'US', 'subdivisionCode' => 'CA']); // Passes
-
Dynamic Factory Validators: Create validators based on input.
v::factory(fn($input) => v::key('confirmation', v::equals($input['password'] ?? null))) ->assert(['password' => 'secret', 'confirmation' => 'secret']); // Passes
-
Prefixed Shortcuts: Convenient wrappers for common patterns.
v::nullOrEmail()->assert(null); // Passes v::allPositive()->assert([1, 2, 3]); // Passes v::notBlank()->assert('hello'); // Passes
-
Result Composition: Nested results for clearer messages (e.g.,
all(v::intType())→ "Every item must be an integer"). -
Paths in Errors: Full dot-notation paths for nested failures (e.g.,
.mysql.host must be a string). -
Helpful Stack Traces: Traces point to user code, not library internals.
-
Custom Exceptions: Pass exceptions to
assert().v::email()->assert($input, new DomainException('Invalid email'));
-
Placeholder Pipes: Customize template rendering (e.g.,
{{haystack|list:or}}→ "active" or "pending"). -
Symfony Translation: Uses Symfony contracts for message translation.
-
New Validators:
All,BetweenExclusive,ContainsCount,DateTimeDiff,Formatted,Hetu,KeyExists,KeyOptional,Named,PropertyExists,PropertyOptional,Templated.
For more details, see the Feature Guide, Validators List, or open an issue on GitHub.