PHPackages                             davebugg/validony - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Debugging &amp; Profiling](/categories/debugging)
4. /
5. davebugg/validony

ActiveLibrary[Debugging &amp; Profiling](/categories/debugging)

davebugg/validony
=================

Powerful and flexible PHP data validator with customizable rules, error messages, and callback functions

v2.0.1(11mo ago)119MITPHPPHP &gt;=8.0.0

Since Mar 31Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/DaveBugg/Validony)[ Packagist](https://packagist.org/packages/davebugg/validony)[ Docs](https://github.com/DaveBugg/Validony)[ RSS](/packages/davebugg-validony/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)DependenciesVersions (4)Used By (0)

Validony
========

[](#validony)

Powerful and Flexible PHP Data Validator
----------------------------------------

[](#powerful-and-flexible-php-data-validator)

[![PHP Version](https://camo.githubusercontent.com/f32695bd6f65b12545162e869707d33dac6bcb5f6e5dc0d48b6d1f8162b6c247/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e302d626c75652e737667)](https://php.net/)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

Validony is a modern PHP library for data validation that provides flexible capabilities for validating data arrays with customizable rules, error messages, and callback functions.

🚀 Features
----------

[](#-features)

- ✅ **Array data validation** with customizable rules
- ✅ **Similar field name validation** (e.g., `password_1`, `password_2`)
- ✅ **Flexible error message system** with multi-language support
- ✅ **Customizable callback functions** for error handling
- ✅ **Static and dynamic methods** for usage
- ✅ **Support for custom validation classes**
- ✅ **Get all errors or stop on first error**

> **⚠️ IMPORTANT:** The default `Checker`, `Messages`, and `Lists` classes included with this library are **examples only**. For production applications, you should create your own custom classes with validation rules, error messages, and field names specific to your application's needs.

📦 Installation
--------------

[](#-installation)

```
composer require davebugg/validony
```

🔧 Quick Start
-------------

[](#-quick-start)

### Basic Usage

[](#basic-usage)

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

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

// Define validation rules
$rules = [
    'email' => [Checker::required, Checker::email],
    'password' => [Checker::required, Checker::password],
    'age' => [Checker::numeric]
];

// Perform validation
$validator->CheckData($rules);

// Check result
if ($validator->isValid()) {
    echo "Data is valid!";
} else {
    $errors = $validator->getErrors();
    print_r($errors);
}
```

🏗️ Custom Classes - **RECOMMENDED APPROACH**
--------------------------------------------

[](#️-custom-classes---recommended-approach)

**⚠️ Important:** For production applications, it's **highly recommended** to create your own custom classes instead of using the default ones. This gives you full control over validation logic, error messages, and field names.

### 1. Custom Checker Class

[](#1-custom-checker-class)

Create your own validation methods class based on the default `Checker` class:

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

class MyChecker
{
    // Define constants for your validation rules
    public const required = 'required';
    public const email = 'email';
    public const password = 'password';
    public const username = 'username';
    public const age = 'age';
    public const phone = 'phone';

    // Custom validation methods
    public static function required($val): bool
    {
        return !empty($val) && $val !== null && $val !== '';
    }

    public static function email($val): bool
    {
        return filter_var($val, FILTER_VALIDATE_EMAIL) !== false;
    }

    public static function password($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 = 13 && strlen($val)  [
            'required' => 'The :field field is required',
            'email' => 'The :field must be a valid email address',
            'password' => 'The :field must be at least 8 characters long',
            'numeric' => 'The :field must be a number',
            'minLength' => 'The :field must be at least :min characters long',
            'maxLength' => 'The :field must not exceed :max characters'
        ],
        'es' => [
            'required' => 'El campo :field es obligatorio',
            'email' => 'El :field debe ser una dirección de email válida',
            'password' => 'La :field debe tener al menos 8 caracteres',
            'numeric' => 'El :field debe ser un número',
            'minLength' => 'El :field debe tener al menos :min caracteres',
            'maxLength' => 'El :field no debe exceder :max caracteres'
        ],
        'fr' => [
            'required' => 'Le champ :field est requis',
            'email' => 'Le :field doit être une adresse email valide',
            'password' => 'Le :field doit contenir au moins 8 caractères',
            'numeric' => 'Le :field doit être un nombre',
            'minLength' => 'Le :field doit contenir au moins :min caractères',
            'maxLength' => 'Le :field ne doit pas dépasser :max caractères'
        ],
        'ru' => [
            'required' => 'Поле :field обязательно для заполнения',
            'email' => 'Поле :field должно содержать корректный email адрес',
            'password' => 'Поле :field должно содержать минимум 8 символов',
            'numeric' => 'Поле :field должно быть числом',
            'minLength' => 'Поле :field должно содержать минимум :min символов',
            'maxLength' => 'Поле :field не должно превышать :max символов'
        ]
    ];

    public static array $fieldNames = [
        'en' => [
            'email' => 'Email Address',
            'password' => 'Password',
            'username' => 'Username',
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'phone' => 'Phone Number'
        ],
        'es' => [
            'email' => 'Dirección de Email',
            'password' => 'Contraseña',
            'username' => 'Nombre de Usuario',
            'first_name' => 'Nombre',
            'last_name' => 'Apellido',
            'phone' => 'Número de Teléfono'
        ],
        'fr' => [
            'email' => 'Adresse Email',
            'password' => 'Mot de passe',
            'username' => 'Nom d\'utilisateur',
            'first_name' => 'Prénom',
            'last_name' => 'Nom de famille',
            'phone' => 'Numéro de téléphone'
        ],
        'ru' => [
            'email' => 'Email адрес',
            'password' => 'Пароль',
            'username' => 'Имя пользователя',
            'first_name' => 'Имя',
            'last_name' => 'Фамилия',
            'phone' => 'Номер телефона'
        ]
    ];
}
```

### 3. Custom Lists Classes

[](#3-custom-lists-classes)

Create organized validation rule sets for different forms:

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

use App\Validators\MyChecker;

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

    public static function login(): array
    {
        return [
            'email' => [MyChecker::required, MyChecker::email],
            'password' => [MyChecker::required]
        ];
    }

    public static function profile(): array
    {
        return [
            'first_name' => [MyChecker::required],
            'last_name' => [MyChecker::required],
            'email' => [MyChecker::required, MyChecker::email],
            'phone' => [MyChecker::phone],
            'age' => [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::required, MyChecker::email],
            'phone' => [MyChecker::required, MyChecker::phone],
            'zipCode' => [MyChecker::required, MyChecker::zipCode],
            'creditCard' => [MyChecker::required, MyChecker::creditCard]
        ];
    }

    public static function shipping(): array
    {
        return [
            'first_name' => [MyChecker::required],
            'last_name' => [MyChecker::required],
            'address' => [MyChecker::required],
            'city' => [MyChecker::required],
            'zipCode' => [MyChecker::required, MyChecker::zipCode]
        ];
    }
}
```

### 4. Using Custom Classes

[](#4-using-custom-classes)

Now use your custom classes with Validony:

```
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::required, MyChecker::username],
    'email' => [MyChecker::required, MyChecker::email],
    'password' => [MyChecker::required, MyChecker::password],
    'age' => [MyChecker::required, MyChecker::age]
];

$validator->CheckData($rules);

if ($validator->isValid()) {
    echo "Registration successful!";
} else {
    $errors = $validator->getErrors(true);
    foreach ($errors['errors'] as $error) {
        echo $error . "\n";
    }
}

// Method 2: Using validation lists with custom path and namespace
$validator = new Validony(
    $_POST,
    MyMessages::$messages,
    MyMessages::$fieldNames,
    MyChecker::class,
    [],
    'en',
    true,
    false,
    true,
    false
);

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

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

### 5. Complete Example with Custom Classes

[](#5-complete-example-with-custom-classes)

```
// 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 include values (security)
            true,                             // Collect all errors
            false                             // Handle errors manually
        );

        // Use validation list for registration
        $validator->ValidateList(
            'registration',
            'app/Validators/Lists/',
            'App\\Validators\\Lists\\'
        );

        if ($validator->isValid()) {
            // Process registration
            $this->createUser($_POST);

            echo json_encode([
                'success' => true,
                'message' => 'Registration successful!'
            ]);
        } else {
            $errors = $validator->getErrors(true);

            echo json_encode([
                'success' => false,
                'errors' => $errors['errors'],
                'fields' => $errors['fields']
            ]);
        }
    }

    public function handleValidationError($message)
    {
        // Log validation error
        error_log("Validation failed: " . $message);

        // You can add additional error handling here
        // For example, send to monitoring service
    }

    private function createUser($data)
    {
        // Your user creation logic here
    }
}
```

🛠 Constructor and Settings
--------------------------

[](#-constructor-and-settings)

### Constructor Parameters

[](#constructor-parameters)

```
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
)
```

### Detailed Parameter Description

[](#detailed-parameter-description)

ParameterTypeDefaultDescription`$post``array`-**Required.** Data array to validate (usually `$_POST`)`$customMessagesMass``array|bool``false`Custom error messages array`$customFieldName``array|bool``false`Array for renaming fields in messages`$checkerClass``mixed``Checker::class`Class containing validation methods`$callback``array``[]`Array `[class, method]` for callback function`$errLanguage``string``'en'`Language for error messages`$printField``bool``true`Include field name in error message`$printData``bool``false`Include field value in error message`$getAllErrors``bool``false`Collect all errors (`true`) or stop on first (`false`)`$doCallback``bool``false`Automatically call callback when error is found📋 Validation Methods
--------------------

[](#-validation-methods)

### 1. CheckData() - Main Validation

[](#1-checkdata---main-validation)

Validates data according to specified rules.

```
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
)
```

**Example:**

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

$rules = [
    'username' => [Checker::required, Checker::minLength],
    'email' => [Checker::required, Checker::email],
    'password' => [Checker::required, Checker::password]
];

// Use constructor settings
$validator->CheckData($rules);

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

### 2. ValidateList() - Validation via Rule Lists

[](#2-validatelist---validation-via-rule-lists)

Uses predefined rule lists from classes in the Lists folder.

**⚠️ Important:** The `ValidateList` method will use the `Checker` class specified in the constructor. If you pass a custom `$checkerClass` to the constructor, your Lists classes should reference that custom checker, not the default `Checker` class.

```
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
)
```

**Example with Default Checker:**

```
// 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::required, Checker::login], // Uses default Checker
            'email' => [Checker::required, Checker::email],
            'password' => [Checker::required, Checker::password],
            'confirm_password' => [Checker::required]
        ];
    }
}

// Usage with default Checker
$validator = new Validony($_POST); // Uses default Checker::class
$validator->ValidateList('registrationRules');

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

**Example with Custom Checker (RECOMMENDED):**

```
// 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::required, MyChecker::username], // Uses YOUR custom Checker
            'email' => [MyChecker::required, MyChecker::email],
            'password' => [MyChecker::required, MyChecker::password],
            'confirm_password' => [MyChecker::required]
        ];
    }
}

// Usage with custom Checker
$validator = new Validony(
    $_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!";
}
```

**How it works:**

1. Validony looks for the specified method (`registrationRules`) in classes within the Lists folder
2. The method returns an array of validation rules
3. Each rule references methods from the Checker class specified in the constructor
4. If you use `MyChecker::class` in constructor, your Lists should use `MyChecker::methodName`
5. If you use default `Checker::class` (or `false`), your Lists should use `Checker::methodName`

### 3. CheckLikeFieldsData() - Similar Fields Validation

[](#3-checklikefieldsdata---similar-fields-validation)

```
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
)
```

**Example:**

```
// Data
$_POST = [
    'password_1' => 'secret123',
    'password_2' => 'secret456',
    'password_new' => 'newsecret',
    'email' => 'test@example.com'
];

// Rules for fields starting with 'password'
$rules = [
    'password' => [Checker::required, Checker::password]
];

$validator = new Validony($_POST);
$validator->CheckLikeFieldsData($rules);

// Will check password_1, password_2, password_new
```

📤 Getting Results
-----------------

[](#-getting-results)

### isValid() - Check Validity

[](#isvalid---check-validity)

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

### getErrors() - Get Errors

[](#geterrors---get-errors)

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

**Parameters:**

- `$getFields` - if `true`, also returns field names with errors

**Examples:**

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

// Errors with field names
$errorsWithFields = $validator->getErrors(true);
// Result: [
//     'errors' => ['Email is invalid', 'Password is required'],
//     'fields' => ['email', 'password']
// ]
```

🎯 Static Methods
----------------

[](#-static-methods)

For quick usage without creating class instance.

### Validon::CheckData()

[](#validoncheckdata)

```
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
);
```

### Validon::ValidateList()

[](#validonvalidatelist)

```
[$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
);
```

🔧 Configuration Examples
------------------------

[](#-configuration-examples)

### Minimal Setup (NOT RECOMMENDED for production)

[](#minimal-setup-not-recommended-for-production)

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

### Recommended Production Setup

[](#recommended-production-setup)

```
// 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 Debugging

[](#development-setup-with-debugging)

```
// 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
);
```

### Multi-Environment Configuration

[](#multi-environment-configuration)

```
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);
```

🔧 Advanced Examples
-------------------

[](#-advanced-examples)

### Example 1: Complete Registration System

[](#example-1-complete-registration-system)

```
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 include values (security)
            true,                             // Collect all errors
            false                             // Handle errors manually
        );

        // Use validation list for registration
        $validator->ValidateList(
            'registration',
            'app/Validators/Lists/',
            'App\\Validators\\Lists\\'
        );

        if ($validator->isValid()) {
            // Process registration
            $this->createUser($_POST);

            echo json_encode([
                'success' => true,
                'message' => 'Registration successful!'
            ]);
        } else {
            $errors = $validator->getErrors(true);

            echo json_encode([
                'success' => false,
                'errors' => $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
    }
}
```

### Example 2: Multiple Fields Validation

[](#example-2-multiple-fields-validation)

```
// 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::required, MyChecker::minLength],
    'product_price' => [MyChecker::required, MyChecker::numeric],
    'product_description' => [MyChecker::required]
];

$validator->CheckLikeFieldsData($rules);

if ($validator->isValid()) {
    echo "All products are valid!";
} else {
    $errors = $validator->getErrors(true);
    echo "Errors found in fields: " . implode(', ', $errors['fields']);
}
```

🌐 Multi-language Support
------------------------

[](#-multi-language-support)

### Using Your Custom Messages Class (RECOMMENDED)

[](#using-your-custom-messages-class-recommended)

The best approach is to create your own Messages class with all the languages and messages you need:

```
// app/Validators/MyMessages.php
namespace App\Validators;

class MyMessages
{
    public static array $messages = [
        'en' => [
            'required' => 'The :field field is required',
            'email' => 'The :field must be a valid email address',
            'password' => 'The :field must be at least 8 characters long',
            'numeric' => 'The :field must be a number',
            'minLength' => 'The :field must be at least :min characters long',
            'maxLength' => 'The :field must not exceed :max characters'
        ],
        'es' => [
            'required' => 'El campo :field es obligatorio',
            'email' => 'El :field debe ser una dirección de email válida',
            'password' => 'La :field debe tener al menos 8 caracteres',
            'numeric' => 'El :field debe ser un número',
            'minLength' => 'El :field debe tener al menos :min caracteres',
            'maxLength' => 'El :field no debe exceder :max caracteres'
        ],
        'fr' => [
            'required' => 'Le champ :field est requis',
            'email' => 'Le :field doit être une adresse email valide',
            'password' => 'Le :field doit contenir au moins 8 caractères',
            'numeric' => 'Le :field doit être un nombre',
            'minLength' => 'Le :field doit contenir au moins :min caractères',
            'maxLength' => 'Le :field ne doit pas dépasser :max caractères'
        ],
        'ru' => [
            'required' => 'Поле :field обязательно для заполнения',
            'email' => 'Поле :field должно содержать корректный email адрес',
            'password' => 'Поле :field должно содержать минимум 8 символов',
            'numeric' => 'Поле :field должно быть числом',
            'minLength' => 'Поле :field должно содержать минимум :min символов',
            'maxLength' => 'Поле :field не должно превышать :max символов'
        ]
    ];

    public static array $fieldNames = [
        'en' => [
            'email' => 'Email Address',
            'password' => 'Password',
            'username' => 'Username',
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'phone' => 'Phone Number'
        ],
        'es' => [
            'email' => 'Dirección de Email',
            'password' => 'Contraseña',
            'username' => 'Nombre de Usuario',
            'first_name' => 'Nombre',
            'last_name' => 'Apellido',
            'phone' => 'Número de Teléfono'
        ],
        'fr' => [
            'email' => 'Adresse Email',
            'password' => 'Mot de passe',
            'username' => 'Nom d\'utilisateur',
            'first_name' => 'Prénom',
            'last_name' => 'Nom de famille',
            'phone' => 'Numéro de téléphone'
        ],
        'ru' => [
            'email' => 'Email адрес',
            'password' => 'Пароль',
            'username' => 'Имя пользователя',
            'first_name' => 'Имя',
            'last_name' => 'Фамилия',
            'phone' => 'Номер телефона'
        ]
    ];
}

// Usage with different languages
$validator = new Validony(
    $_POST,
    MyMessages::$messages,
    MyMessages::$fieldNames,
    MyChecker::class,
    [],
    'es'  // Use Spanish language
);
```

### Dynamic Language Switching

[](#dynamic-language-switching)

```
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');
```

🔍 Debugging and Logging
-----------------------

[](#-debugging-and-logging)

### Enable Detailed Messages

[](#enable-detailed-messages)

```
$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
);
```

### Custom Error Handler

[](#custom-error-handler)

```
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
);
```

📚 API Reference
---------------

[](#-api-reference)

### Main Methods

[](#main-methods)

MethodDescriptionReturns`__construct()`Create validator instance`void``CheckData()`Validate by rules`bool``ValidateList()`Validate via rule lists`void``CheckLikeFieldsData()`Validate similar fields`bool``isValid()`Check validation result`bool``getErrors()`Get errors`array`### Static Methods

[](#static-methods)

MethodDescriptionReturns`Validon::CheckData()`Static validation`array``Validon::ValidateList()`Static validation via lists`array``Validon::CheckLikeFieldsData()`Static validation of similar fields`array`🤝 Contributing
--------------

[](#-contributing)

We welcome contributions to the project! Please:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

📄 License
---------

[](#-license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

🆘 Support
---------

[](#-support)

Need help? We're here for you:

- Create an [Issue](https://github.com/DaveBugg/Validony/issues)
- Check the [Wiki](https://github.com/DaveBugg/Validony/wiki)

🔗 Links
-------

[](#-links)

- [Documentation](https://github.com/DaveBugg/Validony/wiki)
- [Changelog](CHANGELOG.md)

---

**Validony** - Making data validation simple and powerful! 🚀

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance73

Regular maintenance activity

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~32 days

Total

3

Last Release

348d ago

Major Versions

1.0.4 → 2.0.02025-06-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/8bfe6b973caee39d4071146175d86a87a322267b134a296e0b5230c7acc97241?d=identicon)[DaveBugg](/maintainers/DaveBugg)

---

Top Contributors

[![DaveBugg](https://avatars.githubusercontent.com/u/44900378?v=4)](https://github.com/DaveBugg "DaveBugg (34 commits)")

---

Tags

backend-validationcomposer-packagecustom-rulesdata-validationerror-handlingform-validationinput-validationinput-validation-librarymultilingualphpphp-libraryphp8validatevalidationvalidation-libraryvalidation-toolvalidatorphpvalidatorvalidationcallbackrulesform validationdata validationarray validation

### Embed Badge

![Health badge](/badges/davebugg-validony/health.svg)

```
[![Health](https://phpackages.com/badges/davebugg-validony/health.svg)](https://phpackages.com/packages/davebugg-validony)
```

###  Alternatives

[codezero/laravel-unique-translation

Check if a translated value in a JSON column is unique in the database.

186965.1k7](/packages/codezero-laravel-unique-translation)[blakvghost/php-validator

PHPValidator is a modern PHP library for data validation in your PHP applications. It provides a flexible and extensible way to validate data using predefined rules or by creating custom validation rules.

2524.2k2](/packages/blakvghost-php-validator)[iutrace/laravel-cuit-validator

Argentinian CUIT and CUIL Validator

1013.3k](/packages/iutrace-laravel-cuit-validator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
