Examples - Core
Implementation examples using the framework-agnostic core library.
Source code:
packages/example/core/
1. Basic Validation
Define a field schema and validate input values with Validator.
php
<?php
/**
* Example: Basic validation
* Run: php example/core/01-validate.php
*/
require_once __DIR__ . '/../../vendor/autoload.php';
use Respect\Validation\Validator as v;
use SchemableValidator\Orchestration\Validator;
$schema = [
'name' => v::stringType()->length(1, 50),
'email' => v::email(),
'body' => v::stringType()->length(1, 1000),
];
// --- Valid ---
$result = (new Validator($schema))
->validate(['name' => 'Alice', 'email' => 'alice@example.com', 'body' => 'Hello!'])
->getResult();
echo "=== Valid ===\n";
foreach ($result as $field => $state) {
echo "{$field}: " . ($state['is_valid'] ? 'OK' : 'NG') . "\n";
}
// --- Invalid ---
$result = (new Validator($schema))
->validate(['name' => '', 'email' => 'not-an-email', 'body' => ''])
->getResult();
echo "\n=== Invalid ===\n";
foreach ($result as $field => $state) {
echo "{$field}: " . ($state['is_valid'] ? 'OK' : "NG — {$state['errors']}") . "\n";
}2. File Upload Validation
Use validateFiles() to validate the extension and error code of uploaded files.
php
<?php
/**
* Example: File upload validation
* Run: php example/core/02-validate-files.php
*/
require_once __DIR__ . '/../../vendor/autoload.php';
use Respect\Validation\Validator as v;
use SchemableValidator\Orchestration\Validator;
$schema = [
'attachment' => v::key('error', v::equals(UPLOAD_ERR_OK))
->key('name', v::oneOf(v::extension('jpg'), v::extension('png'))),
];
// Simulate a valid uploaded file (native_files: false skips PHP's multi-upload normalization)
$files = [
'attachment' => [[
'name' => 'photo.jpg',
'type' => 'image/jpeg',
'tmp_name' => '',
'error' => UPLOAD_ERR_OK,
'size' => 204800,
]],
];
$result = (new Validator($schema))
->validateFiles($files, ['native_files' => false])
->getResult();
echo "=== File validation ===\n";
foreach ($result['attachment'] as $i => $state) {
echo "file[{$i}]: " . ($state['is_valid'] ? 'OK' : "NG — {$state['errors']}") . "\n";
}
// Invalid: upload error
$files['attachment'][0]['error'] = UPLOAD_ERR_INI_SIZE;
$result = (new Validator($schema))
->validateFiles($files, ['native_files' => false])
->getResult();
echo "\n=== File with upload error ===\n";
echo "file[0]: " . ($result['attachment'][0]['is_valid'] ? 'OK' : "NG — {$result['attachment'][0]['errors']}") . "\n";3. CAPTCHA Validation (reCAPTCHA v3)
Inject a CaptchaDriver and call validateCaptcha() to verify the score threshold and action name.
php
<?php
/**
* Example: CAPTCHA validation (reCAPTCHA v3)
* Run: php example/core/03-recaptcha.php
*
* Replace YOUR_SECRET with your actual secret key.
* The frontend must send the token via POST (e.g. 'g-recaptcha-response').
*/
require_once __DIR__ . '/../../vendor/autoload.php';
use SchemableValidator\SV;
use SchemableValidator\Adapters\Captcha\ReCaptchaV3Driver;
$schema = SV::object([
'name' => SV::string()->min(1),
]);
$validator = $schema->toValidator([
'captchaDriver' => new ReCaptchaV3Driver('YOUR_SECRET'),
]);
// Simulate: $_POST would contain 'g-recaptcha-response' from the frontend widget.
$post = [
'name' => 'Alice',
'g-recaptcha-response' => 'token-from-frontend',
];
$result = $validator
->validate($post)
->validateCaptcha(['action' => 'contact'])
->getResult();
echo "name: " . ($result['name']['is_valid'] ? 'OK' : 'NG') . "\n";
echo "captcha: " . ($result['captcha']['is_valid'] ? 'OK' : 'NG') . "\n";
if ($result['captcha']['errors']) {
echo "error: " . $result['captcha']['errors'] . "\n";
}4. CSRF Token
Generate a token with createToken() and verify it against form submissions using checkToken().
php
<?php
/**
* Example: CSRF token
* Run: php example/core/04-csrf-token.php
*/
session_start();
require_once __DIR__ . '/../../vendor/autoload.php';
use SchemableValidator\Security\CsrfGuard;
$csrf = new CsrfGuard();
// Step 1: Generate token (form render)
$token = $csrf->createToken();
echo "Token generated: {$token}\n";
$stored = $_SESSION['schv_csrf_tokens']['default']['token'] ?? null;
echo "Stored in session: " . ($stored === $token ? 'yes' : 'no') . "\n";
// Step 2: Verify with correct token (form submit)
echo "\nCorrect token: " . ($csrf->checkToken($token) ? 'valid' : 'invalid') . "\n";
// Step 3: Verify with wrong token
echo "Wrong token: " . ($csrf->checkToken('tampered') ? 'valid' : 'invalid') . "\n";5. Template Rendering
Use the Template class to inject validated session data into an email body.
php
<?php
/**
* Example: Template rendering
* Run: php example/core/05-template.php
*/
session_start();
require_once __DIR__ . '/../../vendor/autoload.php';
use SchemableValidator\Orchestration\Template;
// Simulate validated session data (normally saved by FormController::save())
$_SESSION['sv_session_validated_data'] = [
'contact_name' => ['value' => 'Alice', 'is_valid' => true, 'errors' => null],
'contact_email' => ['value' => 'alice@example.com', 'is_valid' => true, 'errors' => null],
'contact_message' => ['value' => "Hello,\nI have a question.", 'is_valid' => true, 'errors' => null],
];
$template = new Template([
'aliases' => [
'name' => 'contact_name',
'email' => 'contact_email',
'body' => 'contact_message',
],
'templates' => [
'user' => "Dear {name},\nThank you for your inquiry.\n\n---\n{body}\n",
'admin' => "New inquiry from {name} <{email}>\n\n---\n{body}\n",
],
]);
echo "=== User email ===\n" . $template->get('user') . "\n";
echo "=== Admin email ===\n" . $template->get('admin');