Skip to content

Core Concepts

This page covers Valicomb’s core concepts, progressing from basic usage to advanced patterns.


The Validator class is your main entry point for all validation operations. It holds your data, manages validation rules, and collects error messages.

Create an instance with your data, then configure rules:

use Frostybee\Valicomb\Validator;
// Create validator with data array
$v = new Validator([
'email' => 'test@example.com',
'age' => 25
]);
new Validator(
array $data = [], // Data to validate
array $fields = [], // Optional field whitelist
?string $lang = null, // Language code (e.g., 'en', 'fr')
?string $langDir = null // Custom language directory
);

Rules are the building blocks of validation. Each rule checks a specific condition on a field’s value, and many rules accept parameters to customize their behavior.

Validation rules are added using the rule() method:

// Basic rule (no parameters)
$v->rule('required', 'email');
// Rule with one parameter
$v->rule('lengthMin', 'password', 8);
// Rule with multiple parameters
$v->rule('lengthBetween', 'username', 3, 20);
// Rule applied to multiple fields
$v->rule('required', ['email', 'name', 'password']);

The validation process follows these steps:

  1. Create a Validator instance with your data
  2. Define validation rules for fields
  3. Call validate() to run validation
  4. Check the result (true if all rules pass)
  5. Retrieve error messages if validation failed
$v = new Validator($data); // Step 1
$v->rule('required', 'email'); // Step 2
$v->rule('email', 'email'); // Step 2
if ($v->validate()) { // Step 3 & 4
// Validation passed
$validData = $v->data();
} else {
// Validation failed
$errors = $v->errors(); // Step 5
}

Errors are returned as an associative array keyed by field name:

$errors = $v->errors();
// [
// 'email' => ['Email is required', 'Email is not valid'],
// 'age' => ['Age must be an integer']
// ]
// Get errors for specific field
$emailErrors = $v->errors('email');
// ['Email is required', 'Email is not valid']

Now that you understand the basics, let’s explore how to control when validation runs and optimize performance.

By default, empty fields skip validation unless marked as required:

$v = new Validator(['name' => '']);
// This rule won't trigger an error because 'name' is empty
// and not marked as required
$v->rule('alpha', 'name');
// Add required to enforce the field must have a value
$v->rule('required', 'name');
$v->rule('alpha', 'name');

Use optional to validate a field only when it’s present:

$v->rule('optional', 'middle_name');
$v->rule('alpha', 'middle_name'); // Only validated if present

By default, all rules are checked. Enable stopOnFirstFail for performance:

$v = new Validator($_POST);
$v->stopOnFirstFail(true);
$v->rule('required', ['email', 'password']);
// Stops as soon as first rule fails

These patterns help you write cleaner, more maintainable validation code in larger applications.

Define validation rules once, then apply them to multiple datasets using withData():

// Define validation rules once
$baseValidator = new Validator([]);
$baseValidator->rule('required', 'email')
->rule('email', 'email');
// Validate different datasets
$v1 = $baseValidator->withData(['email' => 'user1@example.com']);
$v1->validate(); // true
$v2 = $baseValidator->withData(['email' => 'invalid']);
$v2->validate(); // false
  • Form validation: Define field rules once, validate on each form submission
  • API endpoints: Same validation for POST/PUT requests with different payloads
  • Batch processing: Validate multiple records with identical rules
  • Testing: Reuse validators across test cases

withData() returns a new validator instance with the same rules but fresh data. The original validator remains unchanged:

$base = new Validator([]);
$base->rule('required', 'name');
$v1 = $base->withData(['name' => 'Alice']);
$v2 = $base->withData(['name' => 'Bob']);
// $base, $v1, and $v2 are separate instances
$v1->validate(); // Doesn't affect $base or $v2
// Define reusable user validation
$userValidator = new Validator([]);
$userValidator->forFields([
'email' => ['required', 'email'],
'name' => ['required', ['lengthBetween', 2, 50]],
'age' => ['optional', 'integer', ['min', 18]]
]);
// Validate batch of users
$users = [
['email' => 'alice@example.com', 'name' => 'Alice', 'age' => 25],
['email' => 'bob@example.com', 'name' => 'Bob'],
['email' => 'invalid', 'name' => 'X', 'age' => 15],
];
foreach ($users as $userData) {
$v = $userValidator->withData($userData);
if (!$v->validate()) {
print_r($v->errors());
}
}