PHP code example of davebugg / validony

1. Go to this page and download the library: Download davebugg/validony library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

davebugg / validony example snippets


use DavesValidator\Validator\Validony;
use DavesValidator\Validator\Checker;

// Create validator with basic settings
$validator = new Validony($_POST);

// Define validation rules
$rules = [
    'email' => [Checker::!";
} else {
    $errors = $validator->getErrors();
    print_r($errors);
}

// app/Validators/MyChecker.php
namespace App\Validators;

class MyChecker
{
    // Define constants for your validation rules
    public const 
    public const phone = 'phone';
    
    // Custom validation methods
    public static function val): bool
    {
        // Strong password: min 8 chars, uppercase, lowercase, number, special char
        return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/', $val);
    }
    
    public static function username($val): bool
    {
        // Username: 3-20 chars, letters, numbers, underscore
        return preg_match('/^[a-zA-Z0-9_]{3,20}$/', $val);
    }
    
    public static function age($val): bool
    {
        return is_numeric($val) && $val >= 13 && $val <= 120;
    }
    
    public static function phone($val): bool
    {
        // International phone format
        return preg_match('/^\+?[1-9]\d{1,14}$/', $val);
    }
    
    // Add more custom validation methods as needed
    public static function zipCode($val): bool
    {
        return preg_match('/^\d{5}(-\d{4})?$/', $val); // US ZIP code
    }
    
    public static function creditCard($val): bool
    {
        // Basic credit card validation (Luhn algorithm)
        $val = preg_replace('/\D/', '', $val);
        return strlen($val) >= 13 && strlen($val) <= 19;
    }
}

// app/Validators/Lists/UserValidation.php
namespace App\Validators\Lists;

use App\Validators\MyChecker;

class UserValidation
{
    public static function registration(): array
    {
        return [
            'username' => [MyChecker::Optional field
        ];
    }
    
    public static function login(): array
    {
        return [
            'email' => [MyChecker::::age]
        ];
    }
}

// app/Validators/Lists/OrderValidation.php
namespace App\Validators\Lists;

use App\Validators\MyChecker;

class OrderValidation
{
    public static function checkout(): array
    {
        return [
            'email' => [MyChecker::

use DavesValidator\Validator\Validony;
use App\Validators\MyChecker;
use App\Validators\MyMessages;

// Method 1: Direct validation with custom classes
$validator = new Validony(
    $_POST,                           // Data to validate
    MyMessages::$messages,            // Your custom messages
    MyMessages::$fieldNames,          // Your custom field names
    MyChecker::class,                 // Your custom checker class
    [],                               // Callback (optional)
    'en',                             // Language
    true,                             // Show field names
    false,                            // Don't show values
    true,                             // Get all errors
    false                             // Manual error handling
);

// Define rules using your custom checker
$rules = [
    'username' => [MyChecker::lasses
);

if ($validator->isValid()) {
    echo "User registration is valid!";
} else {
    $errors = $validator->getErrors();
    print_r($errors);
}

// Complete registration form validation example
use DavesValidator\Validator\Validony;
use App\Validators\MyChecker;
use App\Validators\MyMessages;

class RegistrationController
{
    public function register()
    {
        // Custom error handler
        $errorHandler = function($message) {
            header('Content-Type: application/json');
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => $message
            ]);
            exit;
        };

        // Create validator with all custom classes
        $validator = new Validony(
            $_POST,                           // Form data
            MyMessages::$messages,            // Custom error messages
            MyMessages::$fieldNames,          // Custom field names
            MyChecker::class,                 // Custom validation methods
            [$this, 'handleValidationError'], // Custom callback
            'en',                             // Language
            true,                             // Include field names in errors
            false,                            // Don't 
    
    private function createUser($data)
    {
        // Your user creation logic here
    }
}

public function __construct(
    array $post,                        // Data to validate
    array|bool $customMessagesMass = false,  // Custom error messages
    array|bool $customFieldName = false,     // Custom field names
    mixed $checkerClass = false,             // Validation methods class
    array $callback = [],                    // Error handling callback
    string $errLanguage = 'en',              // Error message language
    bool $printField = true,                 // Include field name in message
    bool $printData = false,                 // Include field value in message
    bool $getAllErrors = false,              // Collect all errors or stop on first
    bool $doCallback = false                 // Call callback on error
)

public function CheckData(
    array $fields,              // Validation rules
    mixed $CallBack = null,     // Override callback (null = use constructor setting)
    mixed $printField = null,   // Override printField
    mixed $printData = null,    // Override printData
    bool|null $getAllErrors = null  // Override getAllErrors
)

$validator = new Validony($_POST, false, false, false, [], 'en', true, false, true, false);

$rules = [
    'username' => [Checker:: settings
$validator->CheckData($rules);

// Override settings for specific call
$validator->CheckData($rules, true, false, true, true); // enable callback and getAllErrors

public function ValidateList(
    string $method,                           // Method name returning rules
    bool|string $pathOfLists = false,         // Path to Lists folder
    bool|string $namespaceOfListsClasses = false, // Namespace of Lists classes
    bool|null $callback = null,               // Override callback
    bool|null $printField = null,             // Override printField
    bool|null $printData = null,              // Override printData
    bool|null $getAllErrors = null            // Override getAllErrors
)

// Using default Checker class from the library
use DavesValidator\Validator\Checker;

// Lists/UserValidator.php (using default Checker)
class UserValidator {
    public static function registrationRules(): array {
        return [
            'username' => [Checker::Uses default Checker::class
$validator->ValidateList('registrationRules');

if ($validator->isValid()) {
    echo "Registration successful!";
}

// Using your custom Checker class
use App\Validators\MyChecker;

// app/Validators/Lists/UserValidator.php (using custom Checker)
class UserValidator {
    public static function registrationRules(): array {
        return [
            'username' => [MyChecker::y(
    $_POST,
    MyMessages::$messages,
    MyMessages::$fieldNames,
    MyChecker::class,  // ← This tells Validony to use YOUR custom Checker
    [],
    'en'
);

$validator->ValidateList(
    'registrationRules',
    'app/Validators/Lists/',      // Path to your Lists folder
    'App\\Validators\\Lists\\'   // Namespace of your Lists classes
);

if ($validator->isValid()) {
    echo "Registration successful!";
}

public function CheckLikeFieldsData(
    array $fields,                  // Rules for field prefixes
    bool|null $CallBack = null,     // Override callback
    bool|null $printField = null,   // Override printField
    bool|null $printData = null,    // Override printData
    bool|null $getAllErrors = null  // Override getAllErrors
)

// Data
$_POST = [
    'password_1' => 'secret123',
    'password_2' => 'secret456',
    'password_new' => 'newsecret',
    'email' => '[email protected]'
];

// Rules for fields starting with 'password'
$rules = [
    'password' => [Checker::

$isValid = $validator->isValid(); // true/false

public function getErrors(bool $getFields = false): array

// Errors only
$errors = $validator->getErrors();
// Result: ['errors' => ['Email is invalid', 'Password is > ['Email is invalid', 'Password is 

use DavesValidator\Validator\Validon;

[$isValid, $errors] = Validon::CheckData(
    $_POST,                    // Data
    $rules,                    // Rules
    false,                     // Custom messages
    false,                     // Custom field names
    false,                     // Checker class
    [],                        // Callback
    false,                     // Call callback
    'en',                      // Language
    true,                      // Print field name
    false,                     // Print value
    false,                     // All errors
    false                      // Get fields with errors
);

[$isValid, $errors] = Validon::ValidateList(
    $_POST,                    // Data
    'registrationRules',       // Method with rules
    false,                     // Custom messages
    false,                     // Custom field names
    false,                     // Checker class
    [],                        // Callback
    false,                     // Call callback
    'en',                      // Language
    false,                     // Path to Lists
    false,                     // Namespace Lists
    true,                      // Print field name
    false,                     // Print value
    false,                     // All errors
    false                      // Get fields with errors
);

// Uses default library classes - only for testing/development
$validator = new Validony($_POST);
$validator->CheckData($rules);

// Use your own custom classes for production
$validator = new Validony(
    $_POST,                           // Data
    MyMessages::$messages,            // Your custom messages
    MyMessages::$fieldNames,          // Your custom field names
    MyChecker::class,                 // Your custom checker
    [Logger::class, 'log'],           // Error logging
    'en',                             // Language
    true,                             // Show field names
    false,                            // Hide values (security)
    true,                             // Collect all errors
    false                             // Manual error handling
);

// Development setup with detailed debugging
$validator = new Validony(
    $_POST,                           // Data
    MyMessages::$messages,            // Your custom messages (even in dev)
    MyMessages::$fieldNames,          // Your custom field names
    MyChecker::class,                 // Your custom checker
    [Debug::class, 'dump'],           // Debug callback
    'en',                             // Language
    true,                             // Show field names
    true,                             // Show values (debugging)
    true,                             // Collect all errors
    true                              // Auto callback
);

class ValidatorFactory
{
    public static function create($data, $language = 'en')
    {
        $isProduction = $_ENV['APP_ENV'] === 'production';
        
        return new Validony(
            $data,
            MyMessages::$messages,        // Always use custom messages
            MyMessages::$fieldNames,      // Always use custom field names
            MyChecker::class,             // Always use custom checker
            $isProduction 
                ? [Logger::class, 'logError']     // Production: log errors
                : [Debug::class, 'dumpError'],    // Development: dump errors
            $language,
            true,                         // Always show field names
            !$isProduction,               // Show values only in development
            true,                         // Always collect all errors
            $isProduction                 // Auto-callback in production only
        );
    }
}

// Usage
$validator = ValidatorFactory::create($_POST, 'en');
$validator->CheckData($rules);

use DavesValidator\Validator\Validony;
use App\Validators\MyChecker;
use App\Validators\MyMessages;

class RegistrationController
{
    public function register()
    {
        // Create validator with all custom classes
        $validator = new Validony(
            $_POST,                           // Form data
            MyMessages::$messages,            // Custom error messages
            MyMessages::$fieldNames,          // Custom field names
            MyChecker::class,                 // Custom validation methods
            [$this, 'handleValidationError'], // Custom callback
            'en',                             // Language
            true,                             // Include field names in errors
            false,                            // Don't  => $errors['errors'],
                'fields' => $errors['fields']
            ]);
        }
    }
    
    public function handleValidationError($message)
    {
        // Log validation error
        error_log("Validation failed: " . $message);
    }
    
    private function createUser($data)
    {
        // Your user creation logic here
    }
}

// Form data with multiple similar fields
$_POST = [
    'product_name_1' => 'Product 1',
    'product_name_2' => 'Product 2',
    'product_price_1' => '100',
    'product_price_2' => '200',
    'product_description_1' => 'Product 1 description',
    'product_description_2' => 'Product 2 description'
];

$validator = new Validony(
    $_POST, 
    MyMessages::$messages, 
    MyMessages::$fieldNames, 
    MyChecker::class, 
    [], 
    'en', 
    true, 
    false, 
    true
);

// Rules for all fields starting with specific prefixes
$rules = [
    'product_name' => [MyChecker::

class MultiLanguageValidator
{
    private $validator;
    
    public function validateInLanguage($data, $rules, $language = 'en')
    {
        $this->validator = new Validony(
            $data,
            MyMessages::$messages,
            MyMessages::$fieldNames,
            MyChecker::class,
            [],
            $language  // Dynamic language selection
        );
        
        $this->validator->CheckData($rules);
        
        return [
            'valid' => $this->validator->isValid(),
            'errors' => $this->validator->getErrors(true),
            'language' => $language
        ];
    }
}

// Usage
$multiValidator = new MultiLanguageValidator();

// Validate in English
$result_en = $multiValidator->validateInLanguage($_POST, $rules, 'en');

// Validate in Spanish
$result_es = $multiValidator->validateInLanguage($_POST, $rules, 'es');

// Validate in Russian
$result_ru = $multiValidator->validateInLanguage($_POST, $rules, 'ru');

$validator = new Validony(
    $_POST,
    MyMessages::$messages,  // Use your custom messages even for debugging
    MyMessages::$fieldNames,
    MyChecker::class,       // Use your custom checker
    [],
    'en',
    true,   // Show field names
    true,   // Show field values (for debugging)
    true,   // Collect all errors
    false
);

class DebugErrorHandler {
    public static function logError($message) {
        $timestamp = date('Y-m-d H:i:s');
        $logMessage = "[{$timestamp}] Validation Error: {$message}\n";
        file_put_contents('validation.log', $logMessage, FILE_APPEND);
    }
}

$validator = new Validony(
    $_POST,
    MyMessages::$messages,
    MyMessages::$fieldNames,
    MyChecker::class,
    [DebugErrorHandler::class, 'logError'],
    'en',
    true,
    true,
    true,
    true  // Automatically call callback
);