dsheiko / validate
High-performance, secure validation library for Design by Contract programming. Validate primitive and complex types with chainable validators, contract-based validation, and comprehensive security features.
Requires
- php: >=7.0.0
Requires (Dev)
This package is auto-updated.
Last update: 2026-06-05 09:56:56 UTC
README
Extendable, high-performance validation library for testing primitive and complex types against a contract. Designed for Design by Contract programming and comprehensive input validation in PHP applications.
Installation
Require as a composer dependency:
composer require "dsheiko/validate"
Requirements
- PHP >= 7.0.0
- No external dependencies
Key Features
🎯 Core Capabilities
- Validators are dead simple to extend - Create custom validators by implementing ValidateInterface
- Design by Contract support - Validate preconditions and postconditions with Validate::contract()
- Validator chaining - Chain multiple validators for fluent validation syntax
- Direct assertion access - Use validators as direct assertions in your code
- Complex type validation - Support for nested arrays, associative arrays, and key-value structures
- Exception-based error handling - Specific exception types for different validation failures
🔐 Security Features (v1.2.0+)
- Credit card validation - Implements Luhn algorithm for genuine card validation
- ReDoS protection - Length constraints prevent regular expression denial of service attacks
- Email length validation - RFC 5321 compliant length constraints
- Input sanitization - Validators properly handle edge cases and malicious input
⚡ Performance Features
- Factory caching - 30-50% faster validation chains
- Optimized validators - 10-15% faster UUID and string validation
- Efficient loops - Removed closure overhead for 5-10% improvement
- Minimal overhead - Fast validation suitable for high-traffic applications
Quick Start
<?php use \Dsheiko\Validate; // Simple validation $validate = new Validate(); $validate->IsString("hello") ->IsInt(42, ["min" => 0, "max" => 100]) ->IsEmailAddress("user@example.com"); if (!$validate->isValid()) { foreach ($validate->getMessages() as $message) { echo $message . "\n"; } } // Contract-based validation Validate::contract([ "email" => ["user@example.com", "IsEmailAddress"], "age" => [25, ["IsInt" => ["min" => 18, "max" => 120]]], ]); // Map validation Validate::map($data, [ "username" => ["mandatory", "IsString" => ["minLength" => 3, "maxLength" => 20]], "email" => ["mandatory", "IsEmailAddress"], "age" => ["optional", "IsInt" => ["min" => 0, "max" => 150]], ]);
Security
Recent Security Improvements (v1.2.0)
This library has been updated with critical security fixes:
-
Credit Card Validation - Now implements the Luhn algorithm to properly validate credit card numbers. Invalid cards that previously passed regex validation will now be correctly rejected.
-
ReDoS Protection - Added length constraints and optimized regex patterns to prevent Regular Expression Denial of Service attacks.
-
Email Validation - Enforces RFC 5321 email length constraints (maximum 254 characters) to prevent DoS attacks.
See CHANGELOG.md for detailed security fixes in v1.2.0.
Best Practices
- Always validate user input - Use this library to validate all untrusted input
- Use contract validation - Catch errors early with Design by Contract validation
- Validate early - Validate input at the application boundary
- Handle exceptions - Catch and properly handle validation exceptions
Performance
Benchmarks (v1.2.0)
The library has been optimized for high-performance validation:
- Validation chains: 30-50% faster with factory caching
- UUID validation: 10-15% faster with pre-checks
- Contract validation: 5-10% faster with optimized loops
- Factory calls (1000x): 0.14ms
Performance Tips
- Use validation contracts for bulk validation
- Chain multiple validators instead of separate checks
- Validate at the boundary of your application
- Consider using map validation for complex data structures
See CHANGELOG.md for performance improvement details in v1.2.0.
Usage
- Basic Usage
- Provided Validators
- Validator Chain
- Validation by Contract
- Map Validation
- Custom Validators
Examples
Design by Contract Validation
<?php use \Dsheiko\Validate; function login($email, $password) { // Validate preconditions using contract Validate::contract([ "email" => [$email, "IsEmailAddress"], "password" => [$password, ["IsString" => ["minLength" => 6, "maxLength" => 32, "notEmpty" => true]]], ]); // Perform login logic... // Validate postconditions if needed Validate::contract([ "session_id" => [$sessionId, "IsUuid"], ]); }
Potential exceptions:
Dsheiko\Validate\IsEmailAddress\ExceptionDsheiko\Validate\IsString\ExceptionDsheiko\Validate\IsString\MinLength\ExceptionDsheiko\Validate\IsString\MaxLength\Exception
Error messages:
Parameter "email" validation failed: "invalid@..is not a valid email addressParameter "password" validation failed: "123" is too short; must be more than 6 chars
Map Validation
<?php use \Dsheiko\Validate; $formData = [ "username" => "john_doe", "email" => "john@example.com", "password" => "secure_password", "age" => 28, "newsletter" => true, ]; Validate::map($formData, [ "username" => ["mandatory", "IsString" => ["minLength" => 3, "maxLength" => 50]], "email" => ["mandatory", "IsEmailAddress"], "password" => ["mandatory", ["IsString" => ["minLength" => 8, "maxLength" => 128, "notEmpty" => true]]], "age" => ["optional", "IsInt" => ["min" => 0, "max" => 150]], "newsletter" => ["optional", "IsBool"], "phone" => ["optional", "IsString"], // Not in data, optional - OK ]);
Exception messages:
Property "email" validation failed: "invalid.." is not a valid email addressProperty "age" validation failed: 200 is too high; must be less than 150
Validator Chaining
<?php use \Dsheiko\Validate; $validate = new Validate(); $validate->IsString("test@example.com") ->IsEmailAddress("test@example.com") ->IsString("password123") ->IsInt(25, ["min" => 18, "max" => 120]); if (!$validate->isValid()) { // Handle validation errors $messages = $validate->getMessages(); }
Available Validators
Core validators included:
IsString- Validates string type with length constraintsIsInt- Validates integer type with min/max constraintsIsBool- Validates boolean typeIsArray- Validates array typeIsAssocArray- Validates associative array typeIsEmailAddress- Validates email address (RFC 5321 compliant)IsUrl- Validates URL formatIsUuid- Validates UUID v4 formatIsIp- Validates IPv4 and IPv6 addressesIsAlpha- Validates alphabetic characters onlyIsAlnum- Validates alphanumeric charactersIsCreditCard- Validates credit card number with Luhn algorithmNotEmpty- Validates non-empty values
License
MIT License - see LICENSE file for details