Core Concepts
This page covers Valicomb’s core concepts, progressing from basic usage to advanced patterns.
Basics
Section titled “Basics”The Validator Instance
Section titled “The Validator Instance”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]);Constructor Parameters
Section titled “Constructor Parameters”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 and Parameters
Section titled “Rules and Parameters”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']);Validation Flow
Section titled “Validation Flow”The validation process follows these steps:
- Create a
Validatorinstance with your data - Define validation rules for fields
- Call
validate()to run validation - Check the result (
trueif all rules pass) - 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}Error Structure
Section titled “Error Structure”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']Intermediate
Section titled “Intermediate”Now that you understand the basics, let’s explore how to control when validation runs and optimize performance.
Required vs Optional Fields
Section titled “Required vs Optional Fields”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');The Optional Rule
Section titled “The Optional Rule”Use optional to validate a field only when it’s present:
$v->rule('optional', 'middle_name');$v->rule('alpha', 'middle_name'); // Only validated if presentStop on First Failure
Section titled “Stop on First Failure”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 failsAdvanced
Section titled “Advanced”These patterns help you write cleaner, more maintainable validation code in larger applications.
Reusing Validators
Section titled “Reusing Validators”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(); // falseWhy Use withData()
Section titled “Why Use withData()”- 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
How It Works
Section titled “How It Works”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 $v2Complete Example
Section titled “Complete Example”// 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()); }}Next Steps
Section titled “Next Steps”- Defining Rules - Master the three rule syntaxes
- Validation Rules - Explore all 53 built-in rules
- Custom Rules - Create your own validation rules