JSON Schema Validator — PHP source
Validate a JSON document against a draft-07 subset schema: types, required, bounds, patterns, enums, arrays and strict objects, every issue reported at its exact path. Pairs with the schema generator. Runs locally with a shareable link.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
// json-schema-validator — draft-07 SUBSET JSON Schema validator. PHP port
// (canonical TS: src/lib/json-schema-validator.ts; Go twin:
// cli/json-schema-validator). Validates a JSON instance against a schema
// supporting: type (string or array, "integer" counts as "number"), enum,
// const, minimum/maximum/exclusiveMinimum/exclusiveMaximum, minLength/
// maxLength (TS .length counts UTF-16 code units: astral chars are 2),
// pattern, minItems/maxItems, uniqueItems, items, required, properties,
// additionalProperties: false, and the boolean schemas true/false.
// Unsupported keywords ($ref/$defs, oneOf/anyOf/allOf/not, patternProperties,
// dependencies, format, propertyNames, contains) are ignored, exactly like
// the TS lib and the Go twin; the companion generator (json-to-schema) never
// emits any of them. json_decode gives stdClass objects (insertion-ordered
// like JS Object.keys) so issue ordering matches. Numbers print into
// messages with JS Number-to-string rules (70000, 1.5e-7, 1e+21). Patterns
// run through PCRE (preg_match, byte semantics, no 'u' flag). Never throws
// — errors travel in the result array.
declare(strict_types=1);
function jsv_is_num($x): bool
{
return is_int($x) || is_float($x);
}
function jsv_kind($v): string
{
if (is_bool($v)) return 'boolean';
if (is_null($v)) return 'null';
if (is_int($v)) return 'integer';
if (is_float($v)) return is_finite($v) && $v == floor($v) ? 'integer' : 'number';
if (is_array($v)) return 'array'; // with assoc=false json arrays are lists
if ($v instanceof stdClass) return 'object';
return 'string';
}
function jsv_deep_equal($a, $b): bool
{
// Kind-sensitive structural equality; objects compare by key sets.
$ka = jsv_kind($a);
if ($ka !== jsv_kind($b)) return false;
if ($ka === 'array') {
if (count($a) !== count($b)) return false;
$i = 0;
foreach ($a as $x) {
if (!jsv_deep_equal($x, $b[$i])) return false;
$i++;
}
return true;
}
if ($ka === 'object') {
$ao = get_object_vars($a);
$bo = get_object_vars($b);
if (count($ao) !== count($bo)) return false;
foreach ($ao as $k => $x) {
if (!array_key_exists($k, $bo) || !jsv_deep_equal($x, $bo[$k])) return false;
}
return true;
}
if ($ka === 'integer' || $ka === 'number') return (float)$a === (float)$b; // 1 === 1.0 in JS
return $a === $b;
}
// JS Number-to-string: plain integers below 1e21, exponential only past the
// JS thresholds (decimal exponent < -6 or >= 21), minimal exponent digits
// ('1.5e-7', '1e+21').
function jsv_js_num($v): string
{
if (is_int($v)) return (string)$v;
if (is_nan($v)) return 'NaN';
if (is_infinite($v)) return $v > 0 ? 'Infinity' : '-Infinity';
if ($v == 0.0) return '0';
$neg = $v < 0;
$a = abs($v);
if ($a == floor($a) && $a < 1e21) return ($neg ? '-' : '') . (string)(int)$a;
$text = strtolower(json_encode($a)); // serialize_precision=-1: shortest round-trip
if (strpos($text, 'e') !== false) {
[$mant, $e] = explode('e', $text);
$exp = (int)$e;
$digits = str_replace('.', '', $mant);
} else {
$parts = explode('.', $text);
$intpart = $parts[0];
$frac = $parts[1] ?? '';
$digits = $intpart . $frac;
$exp = strlen($intpart) - 1;
while (strlen($digits) > 1 && $digits[0] === '0') {
$digits = substr($digits, 1);
$exp--;
}
}
$sign = $neg ? '-' : '';
$head = $digits[0] . (strlen($digits) > 1 ? '.' . substr($digits, 1) : '');
if ($exp < -6 || $exp >= 21) return $sign . $head . 'e' . ($exp >= 0 ? '+' : '-') . abs($exp);
if ($exp < 0) return $sign . '0.' . str_repeat('0', -$exp - 1) . $digits;
if (strlen($digits) > $exp + 1) {
return $sign . substr($digits, 0, $exp + 1) . '.' . substr($digits, $exp + 1);
}
return $sign . $digits . str_repeat('0', $exp + 1 - strlen($digits));
}
// TS .length counts UTF-16 code units: astral chars (4-byte UTF-8) are 2.
function jsv_utf16_len(string $s): int
{
$n = 0;
$i = 0;
$len = strlen($s);
while ($i < $len) {
$b = ord($s[$i]);
if ($b < 0x80) { $i += 1; $n += 1; }
elseif ($b < 0xE0) { $i += 2; $n += 1; }
elseif ($b < 0xF0) { $i += 3; $n += 1; }
else { $i += 4; $n += 2; }
}
return $n;
}
// JS String(v) for schema type entries and required keys.
function jsv_js_str($v): string
{
if (is_null($v)) return 'null';
if ($v === true) return 'true';
if ($v === false) return 'false';
if (jsv_is_num($v)) return jsv_js_num($v);
if (is_string($v)) return $v;
if (is_array($v)) return implode(',', array_map('jsv_js_str', $v));
return '[object Object]';
}
function jsv_issue(array &$out, string $path, string $message): void
{
$out[] = ['path' => $path, 'message' => $message];
}
// Validate one value against one schema node, appending issues with paths.
// Issue order is part of the contract: type, enum, const, numeric bounds,
// string rules, array rules (uniqueItems before items), object rules
// (required, properties, additionalProperties).
function jsv_validate($v, $schema, string $path, array &$out): void
{
if ($schema === true) return;
if ($schema === false) {
jsv_issue($out, $path, 'no value is allowed here (schema is false)');
return;
}
if (!($schema instanceof stdClass)) {
jsv_issue($out, $path, 'invalid schema node: expected an object or boolean');
return;
}
$s = get_object_vars($schema);
if (array_key_exists('type', $s)) {
$t = $s['type'];
$allowed = is_array($t) ? array_map('jsv_js_str', $t) : [jsv_js_str($t)];
$actual = jsv_kind($v);
$ok = false;
foreach ($allowed as $x) {
if ($x === $actual || ($x === 'number' && $actual === 'integer')) { $ok = true; break; }
}
if (!$ok) {
jsv_issue($out, $path, 'expected type ' . implode('|', $allowed) . ', got ' . $actual);
}
}
if (array_key_exists('enum', $s)) {
$entries = is_array($s['enum']) ? $s['enum'] : [];
$found = false;
foreach ($entries as $e) {
if (jsv_deep_equal($v, $e)) { $found = true; break; }
}
if (!$found) jsv_issue($out, $path, 'value not in enum (' . count($entries) . ' allowed)');
}
if (array_key_exists('const', $s) && !jsv_deep_equal($v, $s['const'])) {
jsv_issue($out, $path, 'value does not match const');
}
if (jsv_is_num($v)) {
$m = $s['minimum'] ?? null;
if (jsv_is_num($m) && $v < $m) {
jsv_issue($out, $path, jsv_js_num($v) . ' is less than minimum ' . jsv_js_num($m));
}
$m = $s['maximum'] ?? null;
if (jsv_is_num($m) && $v > $m) {
jsv_issue($out, $path, jsv_js_num($v) . ' is greater than maximum ' . jsv_js_num($m));
}
$m = $s['exclusiveMinimum'] ?? null;
if (jsv_is_num($m) && $v <= $m) {
jsv_issue($out, $path, jsv_js_num($v) . ' is not greater than exclusiveMinimum ' . jsv_js_num($m));
}
$m = $s['exclusiveMaximum'] ?? null;
if (jsv_is_num($m) && $v >= $m) {
jsv_issue($out, $path, jsv_js_num($v) . ' is not less than exclusiveMaximum ' . jsv_js_num($m));
}
}
if (is_string($v)) {
$n = jsv_utf16_len($v);
$m = $s['minLength'] ?? null;
if (jsv_is_num($m) && $n < $m) {
jsv_issue($out, $path, 'string length ' . $n . ' is less than minLength ' . jsv_js_num($m));
}
$m = $s['maxLength'] ?? null;
if (jsv_is_num($m) && $n > $m) {
jsv_issue($out, $path, 'string length ' . $n . ' is greater than maxLength ' . jsv_js_num($m));
}
$p = $s['pattern'] ?? null;
if (is_string($p)) {
$ok = @preg_match('/' . str_replace('/', '\\/', $p) . '/', $v);
if ($ok === false) {
jsv_issue($out, $path, 'invalid pattern in schema: ' . $p);
} elseif ($ok === 0) {
jsv_issue($out, $path, 'string does not match pattern ' . $p);
}
}
}
if (is_array($v)) {
$n = count($v);
$m = $s['minItems'] ?? null;
if (jsv_is_num($m) && $n < $m) {
jsv_issue($out, $path, 'array length ' . $n . ' is less than minItems ' . jsv_js_num($m));
}
$m = $s['maxItems'] ?? null;
if (jsv_is_num($m) && $n > $m) {
jsv_issue($out, $path, 'array length ' . $n . ' is greater than maxItems ' . jsv_js_num($m));
}
if (($s['uniqueItems'] ?? null) === true) {
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
if (jsv_deep_equal($v[$i], $v[$j])) {
jsv_issue($out, $path . '[' . $j . ']', 'duplicate item (same as index ' . $i . ')');
}
}
}
}
if (array_key_exists('items', $s)) {
foreach ($v as $i => $item) {
jsv_validate($item, $s['items'], $path . '[' . $i . ']', $out);
}
}
}
if ($v instanceof stdClass) {
$o = get_object_vars($v);
$req = $s['required'] ?? null;
if (is_array($req)) {
foreach ($req as $rk) {
$key = jsv_js_str($rk);
if (!array_key_exists($key, $o)) {
jsv_issue($out, $path, 'missing required property "' . $key . '"');
}
}
}
$props = ($s['properties'] ?? null) instanceof stdClass ? get_object_vars($s['properties']) : [];
foreach ($props as $key => $sub) {
if (array_key_exists($key, $o)) {
jsv_validate($o[$key], $sub, $path . '.' . $key, $out);
}
}
if (($s['additionalProperties'] ?? null) === false) {
foreach ($o as $key => $ignored) {
if (!array_key_exists($key, $props)) {
jsv_issue($out, $path . '.' . $key, 'additional property not allowed');
}
}
}
}
}
// Validate a JSON document (instance_raw) against a schema (schema_raw).
// Returns ['valid' => bool, 'issues' => [['path', 'message']], 'error']
// — error is null when the verdict is real (TS: error: null).
function validate_json_schema(string $schema_raw, string $instance_raw): array
{
if (trim($schema_raw) === '' || trim($instance_raw) === '') {
return ['valid' => false, 'issues' => [], 'error' => 'Both a schema and an instance are required'];
}
try {
$schema = json_decode($schema_raw, false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
return ['valid' => false, 'issues' => [], 'error' => 'Schema: ' . ($e->getMessage() ?: 'Invalid JSON')];
}
try {
$instance = json_decode($instance_raw, false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
return ['valid' => false, 'issues' => [], 'error' => 'Instance: ' . ($e->getMessage() ?: 'Invalid JSON')];
}
$issues = [];
jsv_validate($instance, $schema, '$', $issues);
return $issues === []
? ['valid' => true, 'issues' => [], 'error' => null]
: ['valid' => false, 'issues' => $issues, 'error' => null];
}
// Example:
// validate_json_schema(
// '{"type":"object","required":["port"],"properties":{"port":{"type":"integer","minimum":1024}}}',
// '{"port":80}')["issues"]
// → [['path' => '$.port', 'message' => '80 is less than minimum 1024']]
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →