Skip to content

Repository files navigation

Validony

Powerful and Flexible PHP Data Validator

PHP VersionLicense

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

  • 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

composer require davebugg/validony

🔧 Quick Start

Basic Usage

useDavesValidator\Validator\Validony;
useDavesValidator\Validator\Checker;
// Create validator with basic settings$validator = newValidony($_POST);
// Define validation rules$rules = [
'email' => [Checker::required, Checker::email],
'password' => [Checker::required, Checker::password],
'age' => [Checker::numeric]
];
// Perform validation$validator->CheckData($rules);
// Check resultif ($validator->isValid()) {
echo"Data is valid!";
} else {
$errors = $validator->getErrors();
print_r($errors);
}

🏗️ 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

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

// app/Validators/MyChecker.phpnamespaceApp\Validators;
class MyChecker
{
// Define constants for your validation rulespublicconstrequired = 'required';
publicconstemail = 'email';
publicconstpassword = 'password';
publicconstusername = 'username';
publicconstage = 'age';
publicconstphone = 'phone';
// Custom validation methodspublicstaticfunctionrequired($val): bool
{
return !empty($val) && $val !== null && $val !== '';
}
publicstaticfunctionemail($val): bool
{
returnfilter_var($val, FILTER_VALIDATE_EMAIL) !== false;
}
publicstaticfunctionpassword($val): bool
{
// Strong password: min 8 chars, uppercase, lowercase, number, special charreturnpreg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/', $val);
}
publicstaticfunctionusername($val): bool
{
// Username: 3-20 chars, letters, numbers, underscorereturnpreg_match('/^[a-zA-Z0-9_]{3,20}$/', $val);
}
publicstaticfunctionage($val): bool
{
returnis_numeric($val) && $val >= 13 && $val <= 120;
}
publicstaticfunctionphone($val): bool
{
// International phone formatreturnpreg_match('/^\+?[1-9]\d{1,14}$/', $val);
}
// Add more custom validation methods as neededpublicstaticfunctionzipCode($val): bool
{
returnpreg_match('/^\d{5}(-\d{4})?$/', $val); // US ZIP code
}
publicstaticfunctioncreditCard($val): bool
{
// Basic credit card validation (Luhn algorithm)$val = preg_replace('/\D/', '', $val);
returnstrlen($val) >= 13 && strlen($val) <= 19;
}
}

2. Custom Messages Class

Create your own messages class for multilingual error messages:

// app/Validators/MyMessages.phpnamespaceApp\Validators;
class MyMessages
{
publicstaticarray$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 символов'
]
];
publicstaticarray$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

Create organized validation rule sets for different forms:

// app/Validators/Lists/UserValidation.phpnamespaceApp\Validators\Lists;
useApp\Validators\MyChecker;
class UserValidation
{
publicstaticfunctionregistration(): 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
];
}
publicstaticfunctionlogin(): array
{
return [
'email' => [MyChecker::required, MyChecker::email],
'password' => [MyChecker::required]
];
}
publicstaticfunctionprofile(): 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.phpnamespaceApp\Validators\Lists;
useApp\Validators\MyChecker;
class OrderValidation
{
publicstaticfunctioncheckout(): array
{
return [
'email' => [MyChecker::required, MyChecker::email],
'phone' => [MyChecker::required, MyChecker::phone],
'zipCode' => [MyChecker::required, MyChecker::zipCode],
'creditCard' => [MyChecker::required, MyChecker::creditCard]
];
}
publicstaticfunctionshipping(): 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

Now use your custom classes with Validony:

useDavesValidator\Validator\Validony;
useApp\Validators\MyChecker;
useApp\Validators\MyMessages;
// Method 1: Direct validation with custom classes$validator = newValidony(
$_POST, // Data to validate
MyMessages::$messages, // Your custom messages
MyMessages::$fieldNames, // Your custom field names
MyChecker::class, // Your custom checker class
[], // Callback (optional)'en', // Languagetrue, // Show field namesfalse, // Don't show valuestrue, // Get all errorsfalse// 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 = newValidony(
$_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

// Complete registration form validation exampleuseDavesValidator\Validator\Validony;
useApp\Validators\MyChecker;
useApp\Validators\MyMessages;
class RegistrationController
{
publicfunctionregister()
{
// Custom error handler$errorHandler = function($message) {
header('Content-Type: application/json');
http_response_code(400);
echojson_encode([
'success' => false,
'message' => $message
]);
exit;
};
// Create validator with all custom classes$validator = newValidony(
$_POST, // Form data
MyMessages::$messages, // Custom error messages
MyMessages::$fieldNames, // Custom field names
MyChecker::class, // Custom validation methods
[$this, 'handleValidationError'], // Custom callback'en', // Languagetrue, // Include field names in errorsfalse, // Don't include values (security)true, // Collect all errorsfalse// 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);
echojson_encode([
'success' => true,
'message' => 'Registration successful!'
]);
} else {
$errors = $validator->getErrors(true);
echojson_encode([
'success' => false,
'errors' => $errors['errors'],
'fields' => $errors['fields']
]);
}
}
publicfunctionhandleValidationError($message)
{
// Log validation errorerror_log("Validation failed: " . $message);
// You can add additional error handling here// For example, send to monitoring service
}
privatefunctioncreateUser($data)
{
// Your user creation logic here
}
}

🛠 Constructor and Settings

Constructor Parameters

publicfunction __construct(
array$post, // Data to validatearray|bool$customMessagesMass = false, // Custom error messagesarray|bool$customFieldName = false, // Custom field namesmixed$checkerClass = false, // Validation methods classarray$callback = [], // Error handling callbackstring$errLanguage = 'en', // Error message languagebool$printField = true, // Include field name in messagebool$printData = false, // Include field value in messagebool$getAllErrors = false, // Collect all errors or stop on firstbool$doCallback = false// Call callback on error
)

Detailed Parameter Description

ParameterTypeDefaultDescription
$postarray-Required. Data array to validate (usually $_POST)
$customMessagesMassarray|boolfalseCustom error messages array
$customFieldNamearray|boolfalseArray for renaming fields in messages
$checkerClassmixedChecker::classClass containing validation methods
$callbackarray[]Array [class, method] for callback function
$errLanguagestring'en'Language for error messages
$printFieldbooltrueInclude field name in error message
$printDataboolfalseInclude field value in error message
$getAllErrorsboolfalseCollect all errors (true) or stop on first (false)
$doCallbackboolfalseAutomatically call callback when error is found

📋 Validation Methods

1. CheckData() - Main Validation

Validates data according to specified rules.

publicfunction CheckData(
array$fields, // Validation rulesmixed$CallBack = null, // Override callback (null = use constructor setting)mixed$printField = null, // Override printFieldmixed$printData = null, // Override printDatabool|null$getAllErrors = null// Override getAllErrors
)

Example:

$validator = newValidony($_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

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.

publicfunction ValidateList(
string$method, // Method name returning rulesbool|string$pathOfLists = false, // Path to Lists folderbool|string$namespaceOfListsClasses = false, // Namespace of Lists classesbool|null$callback = null, // Override callbackbool|null$printField = null, // Override printFieldbool|null$printData = null, // Override printDatabool|null$getAllErrors = null// Override getAllErrors
)

Example with Default Checker:

// Using default Checker class from the libraryuseDavesValidator\Validator\Checker;
// Lists/UserValidator.php (using default Checker)class UserValidator {
publicstaticfunctionregistrationRules(): 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 = newValidony($_POST); // Uses default Checker::class$validator->ValidateList('registrationRules');
if ($validator->isValid()) {
echo"Registration successful!";
}

Example with Custom Checker (RECOMMENDED):

// Using your custom Checker classuseApp\Validators\MyChecker;
// app/Validators/Lists/UserValidator.php (using custom Checker)class UserValidator {
publicstaticfunctionregistrationRules(): 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 = newValidony(
$_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

publicfunction CheckLikeFieldsData(
array$fields, // Rules for field prefixesbool|null$CallBack = null, // Override callbackbool|null$printField = null, // Override printFieldbool|null$printData = null, // Override printDatabool|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 = newValidony($_POST);
$validator->CheckLikeFieldsData($rules);
// Will check password_1, password_2, password_new

📤 Getting Results

isValid() - Check Validity

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

getErrors() - Get Errors

publicfunction 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

For quick usage without creating class instance.

Validon::CheckData()

useDavesValidator\Validator\Validon;
[$isValid, $errors] = Validon::CheckData(
$_POST, // Data$rules, // Rulesfalse, // Custom messagesfalse, // Custom field namesfalse, // Checker class
[], // Callbackfalse, // Call callback'en', // Languagetrue, // Print field namefalse, // Print valuefalse, // All errorsfalse// Get fields with errors
);

Validon::ValidateList()

[$isValid, $errors] = Validon::ValidateList(
$_POST, // Data'registrationRules', // Method with rulesfalse, // Custom messagesfalse, // Custom field namesfalse, // Checker class
[], // Callbackfalse, // Call callback'en', // Languagefalse, // Path to Listsfalse, // Namespace Liststrue, // Print field namefalse, // Print valuefalse, // All errorsfalse// Get fields with errors
);

🔧 Configuration Examples

Minimal Setup (NOT RECOMMENDED for production)

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

Recommended Production Setup

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

Development Setup with Debugging

// Development setup with detailed debugging$validator = newValidony(
$_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', // Languagetrue, // Show field namestrue, // Show values (debugging)true, // Collect all errorstrue// Auto callback
);

Multi-Environment Configuration

class ValidatorFactory
{
publicstaticfunctioncreate($data, $language = 'en')
{
$isProduction = $_ENV['APP_ENV'] === 'production';
returnnewValidony(
$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 developmenttrue, // Always collect all errors$isProduction// Auto-callback in production only
);
}
}
// Usage$validator = ValidatorFactory::create($_POST, 'en');
$validator->CheckData($rules);

🔧 Advanced Examples

Example 1: Complete Registration System

useDavesValidator\Validator\Validony;
useApp\Validators\MyChecker;
useApp\Validators\MyMessages;
class RegistrationController
{
publicfunctionregister()
{
// Create validator with all custom classes$validator = newValidony(
$_POST, // Form data
MyMessages::$messages, // Custom error messages
MyMessages::$fieldNames, // Custom field names
MyChecker::class, // Custom validation methods
[$this, 'handleValidationError'], // Custom callback'en', // Languagetrue, // Include field names in errorsfalse, // Don't include values (security)true, // Collect all errorsfalse// 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);
echojson_encode([
'success' => true,
'message' => 'Registration successful!'
]);
} else {
$errors = $validator->getErrors(true);
echojson_encode([
'success' => false,
'errors' => $errors['errors'],
'fields' => $errors['fields']
]);
}
}
publicfunctionhandleValidationError($message)
{
// Log validation errorerror_log("Validation failed: " . $message);
}
privatefunctioncreateUser($data)
{
// Your user creation logic here
}
}

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 = newValidony(
$_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

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.phpnamespaceApp\Validators;
class MyMessages
{
publicstaticarray$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 символов'
]
];
publicstaticarray$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 = newValidony(
$_POST,
MyMessages::$messages,
MyMessages::$fieldNames,
MyChecker::class,
[],
'es'// Use Spanish language
);

Dynamic Language Switching

class MultiLanguageValidator
{
private$validator;
publicfunctionvalidateInLanguage($data, $rules, $language = 'en')
{
$this->validator = newValidony(
$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 = newMultiLanguageValidator();
// 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

Enable Detailed Messages

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

Custom Error Handler

class DebugErrorHandler {
publicstaticfunctionlogError($message) {
$timestamp = date('Y-m-d H:i:s');
$logMessage = "[{$timestamp}] Validation Error: {$message}\n";
file_put_contents('validation.log', $logMessage, FILE_APPEND);
}
}
$validator = newValidony(
$_POST,
MyMessages::$messages,
MyMessages::$fieldNames,
MyChecker::class,
[DebugErrorHandler::class, 'logError'],
'en',
true,
true,
true,
true// Automatically call callback
);

📚 API Reference

Main Methods

MethodDescriptionReturns
__construct()Create validator instancevoid
CheckData()Validate by rulesbool
ValidateList()Validate via rule listsvoid
CheckLikeFieldsData()Validate similar fieldsbool
isValid()Check validation resultbool
getErrors()Get errorsarray

Static Methods

MethodDescriptionReturns
Validon::CheckData()Static validationarray
Validon::ValidateList()Static validation via listsarray
Validon::CheckLikeFieldsData()Static validation of similar fieldsarray

🤝 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

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

Need help? We're here for you:

🔗 Links


Validony - Making data validation simple and powerful! 🚀

About

Lightweight and flexible PHP data validation library with customizable rules, multilingual error messages, callback support, and similar-field matching. Requires PHP 8.0+.

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages