<?php
declare(strict_types=1);
require __DIR__ . '/../src/ContextualValidator.php';
use ContextValidate\ContextualValidator;
// Simulate a submitted registration + booking form. Every individual
// field below is well-formed on its own - an ordinary validator would
// let all of this through. The inconsistencies only show up when the
// fields are checked against each other.
$submitted = [
'zip' => '90210-1234', // US-style zip...
'country' => 'FR', // ...but country is France
'phone' => '212-555-0100',
'start_date' => '2026-08-10',
'end_date' => '2026-08-01', // end before start
'age' => '25',
'birthdate' => '1990-03-14', // implies age ~36, not 25
'password' => 'hunter2',
'password_confirmation' => 'hunter3', // typo
'min_price' => '200',
'max_price' => '50', // filter inverted
];
$validator = new ContextualValidator($submitted);
$validator
->postalCodeMatchesCountry('zip', 'country')
->phoneMatchesCountry('phone', 'country')
->dateRange('start_date', 'end_date')
->ageMatchesBirthdate('age', 'birthdate')
->fieldsMatch('password', 'password_confirmation')
->numericRange('min_price', 'max_price');
if ($validator->fails()) {
echo "Form has cross-field inconsistencies:\n\n";
foreach ($validator->errors() as $field => $messages) {
foreach ($messages as $message) {
echo " [{$field}] {$message}\n";
}
}
} else {
echo "All good!\n";
}
|