PHP Classes

File: examples/example.php

Recommend this page to a friend!
  Packages of AKONO Metsam Nathan   Contextual Validator - Cross-Field Coherence Checker   examples/example.php   Download  
File: examples/example.php
Role: Example script
Content type: text/plain
Description: Full working example: a form that fails all 5 rules at once, demonstrating every cross-field check together.
Class: Contextual Validator - Cross-Field Coherence Checker
Validate multiple form fields that are related
Author: By
Last change:
Date: 11 days ago
Size: 1,478 bytes
 

Contents

Class file image Download
<?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";
}