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.

Maintainers

Package info

github.com/dsheiko/validate

pkg:composer/dsheiko/validate

Statistics

Installs: 221

Dependents: 0

Suggesters: 0

Stars: 15

Open Issues: 1

v1.2.0 2026-06-05 09:56 UTC

This package is auto-updated.

Last update: 2026-06-05 09:56:56 UTC


README

Latest Stable Version Total Downloads License

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:

  1. 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.

  2. ReDoS Protection - Added length constraints and optimized regex patterns to prevent Regular Expression Denial of Service attacks.

  3. 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

  1. Use validation contracts for bulk validation
  2. Chain multiple validators instead of separate checks
  3. Validate at the boundary of your application
  4. Consider using map validation for complex data structures

See CHANGELOG.md for performance improvement details in v1.2.0.

Usage

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\Exception
  • Dsheiko\Validate\IsString\Exception
  • Dsheiko\Validate\IsString\MinLength\Exception
  • Dsheiko\Validate\IsString\MaxLength\Exception

Error messages:

  • Parameter "email" validation failed: "invalid@..is not a valid email address
  • Parameter "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 address
  • Property "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 constraints
  • IsInt - Validates integer type with min/max constraints
  • IsBool - Validates boolean type
  • IsArray - Validates array type
  • IsAssocArray - Validates associative array type
  • IsEmailAddress - Validates email address (RFC 5321 compliant)
  • IsUrl - Validates URL format
  • IsUuid - Validates UUID v4 format
  • IsIp - Validates IPv4 and IPv6 addresses
  • IsAlpha - Validates alphabetic characters only
  • IsAlnum - Validates alphanumeric characters
  • IsCreditCard - Validates credit card number with Luhn algorithm
  • NotEmpty - Validates non-empty values

License

MIT License - see LICENSE file for details