gadwinn / validator
Value validation with composable constraints, PHP attributes and logical operators (All, AnyOf, OneOf, Not).
Requires
- php: >=8.3
Requires (Dev)
- phpdocumentor/shim: *
- phpstan/phpstan: *
- phpunit/phpunit: *
- povils/phpmnd: *
- roave/security-advisories: dev-latest@dev
- squizlabs/php_codesniffer: *
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-18 11:22:37 UTC
README
A PHP 8.3+ value validation library. Supports constraint-based validation, PHP Attribute-based validation, and logical composition (AND / OR / XOR / NOT).
Installation
composer require gadwinn/validator
Quick start
use G\Validator\Validator; use G\Validator\Constraint\IsEmail; use G\Validator\Constraint\MinLength; $validator = new Validator([new IsEmail()]); $violations = $validator->validate('user@example.com'); // passes $violations = $validator->validate('not-an-email'); // 1 violation if ($violations->hasViolations()) { foreach ($violations as $v) { echo $v->getPath() . ': ' . $v->getMessage() . PHP_EOL; } }
Constraint-based validation
Pass default constraints to the constructor. Override them per call when needed.
$validator = new Validator([new IsEmail()]); // Uses default constraints $violations = $validator->validate($email); // Overrides default constraints for this call only $violations = $validator->validate($value, [new MinLength(5)]);
Attribute-based validation
When validate() is called on an object with no active constraints, the validator
automatically reads PHP Attributes from:
- Class properties (public, protected, private)
- Promoted constructor parameters (attributes on the parameter, not the property)
- Public parameterless methods (return value is validated)
The path of each violation is set to the property or method name.
use G\Validator\Constraint\IsEmail; use G\Validator\Constraint\MinLength; use G\Validator\Constraint\PasswordStrength; use G\Validator\Constraint\Logical\Not; use G\Validator\Constraint\IsBlank; class CreateUserRequest { public function __construct( #[Not(new IsBlank())] #[IsEmail] public readonly string $email, #[MinLength(8)] #[PasswordStrength(PasswordStrength::THRESHOLD_STRONG)] public readonly string $password, ) {} } $request = new CreateUserRequest(email: 'bad', password: 'weak'); $violations = (new Validator())->validate($request); // → 2 violations: 'email' (IsEmail), 'password' (PasswordStrength)
Available constraints
Type(string $type, ?string $message = null)
Checks the PHP type of the value. Strict - no coercion is performed.
$type value |
Check performed |
|---|---|
'null' |
=== null |
'bool' / 'boolean' |
is_bool() |
'int' / 'integer' |
is_int() |
'float' / 'double' |
is_float() |
'number' |
is_int() or is_float() |
'string' |
is_string() |
'array' |
is_array() |
'object' / 'class' |
is_object() |
'json' |
is_string() + json_validate() |
'email' |
valid email address |
| any class or interface name | $value instanceof MyClass |
new Type('int') new Type('email') new Type(\DateTimeImmutable::class)
IsBlank(?string $message = null)
Passes when the value is null, an empty string, or a whitespace-only string.
new IsBlank() // null or '' new Not(new IsBlank()) // required field
IsEmail(?string $message = null)
Checks that the value is a syntactically valid email address.
new IsEmail() new IsEmail(message: 'Please enter a valid e-mail.')
GreaterThanOrEqual(int|float $threshold, ?string $message = null)
Passes when the value (int or float) is ≥ $threshold.
new GreaterThanOrEqual(0) // non-negative new GreaterThanOrEqual(18) // adult age check
LowerThanOrEqual(int|float $threshold, ?string $message = null)
Passes when the value (int or float) is ≤ $threshold.
new LowerThanOrEqual(100)
MinLength(int $min, ?string $message = null)
Passes when mb_strlen($value) >= $min (strings) or count($value) >= $min (arrays).
new MinLength(3) // at least 3 characters / items
MaxLength(int $max, ?string $message = null)
Passes when mb_strlen($value) <= $max (strings) or count($value) <= $max (arrays).
new MaxLength(255) // database column limit
PasswordStrength(float $minEntropy = PasswordStrength::THRESHOLD_FAIR, ?string $message = null)
Measures password strength via Shannon entropy (bits):
$$H = -\sum p_i \log_2(p_i) \times L$$
where $p_i$ is the relative frequency of each distinct character and $L$ the total length.
Unlike theoretical entropy ($L \times \log_2(C)$), Shannon naturally penalises repetitions:
"aaaaaaaa" scores 0 bits, "abcdefgh" scores ≈ 24 bits. UTF-8 safe.
Use the public preset constants or pass a custom float:
| Constant | Entropy (bits) | Typical example |
|---|---|---|
THRESHOLD_VERY_WEAK |
0.0 | any non-trivial password |
THRESHOLD_WEAK |
20.0 | "abcdefghi" ≈ 28 bits |
THRESHOLD_FAIR (default) |
35.0 | "P@ssw0rd!XYZ1" ≈ 50 bits |
THRESHOLD_STRONG |
55.0 | "P@ssw0rd!XYZ123" ≈ 57 bits |
THRESHOLD_VERY_STRONG |
75.0 | "P@ssw0rd!XYZ12345678" ≈ 84 bits |
new PasswordStrength() // >= 35 bits (FAIR) new PasswordStrength(PasswordStrength::THRESHOLD_STRONG) // >= 55 bits new PasswordStrength(minEntropy: 45.0) // custom threshold
Regex(string $pattern, ?string $message = null)
Checks that the value matches the given PCRE regular expression.
Throws InvalidArgumentException if the pattern is syntactically invalid.
new Regex('/^\d{4}$/') // exactly 4 digits new Regex('/^[a-z]+$/i') // letters only (case-insensitive)
Logical constraints
Combine any ConstraintInterface instances.
All(array $constraints) - AND
All constraints must pass. Collects every violation (fail-all).
This is the default behaviour when multiple constraints are given to Validator::validate().
new All([new MinLength(8), new Regex('/[A-Z]/')])
AnyOf(array $constraints, ?string $message = null) - OR
At least one constraint must pass. Returns a single violation if none pass.
new AnyOf([new IsEmail(), new Regex('/^@\w+$/')])
OneOf(array $constraints, ?string $message = null) - XOR
Exactly one constraint must pass. Fails when zero or more than one passes.
new OneOf([new Type('int'), new Type('float')])
Not(ConstraintInterface $constraint, ?string $message = null) - NOT
The wrapped constraint must fail.
new Not(new IsBlank()) // must not be blank new Not(new IsEmail()) // must not look like an email
Violation objects
Each ViolationInterface exposes:
| Method | Description |
|---|---|
getMessage(): string |
Human-readable error message |
getConstraint(): string |
FQCN of the constraint that triggered the violation |
getPath(): string |
Property / method name (empty for scalar validation) |
getCode(): string |
Short uppercase code, e.g. IS_EMAIL |
getInvalidValue(): mixed |
The value that was rejected |
foreach ($violations as $violation) { echo sprintf( '[%s] %s → %s%s', $violation->getCode(), $violation->getPath() ?: '(root)', $violation->getMessage(), PHP_EOL, ); }
Custom constraints
Implement ConstraintInterface or extend AbstractConstraint:
use G\Validator\Constraint\AbstractConstraint; final class IsUuid extends AbstractConstraint { public const string CODE = 'IS_UUID'; private const string PATTERN = '/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i'; public function __construct(?string $message = null) { $this->message = $message; } protected function isValid(mixed $value): bool { return is_string($value) && preg_match(self::PATTERN, $value) === 1; } protected function getDefaultMessage(): string { return 'The value is not a valid UUID.'; } protected function getConstraintCode(): string { return self::CODE; } }
Contracts
| Interface | Description |
|---|---|
ValidatorInterface |
validate(mixed $value, array $constraints = []): ViolationListInterface |
ConstraintInterface |
validate(mixed $value, string $path = ''): ViolationListInterface |
ViolationListInterface |
Iterable, countable collection of violations |
ViolationInterface |
A single violation |
License
MIT, see LICENSE.