Skip to content

Validate using an inline schema

Danny van der Sluijs edited this page Feb 6, 2024 · 1 revision

About

This library support validating JSON documents using an inline schema.

Pro/Cons

  • + No disk or network i/o required (beyond loading the PHP code)
  • - Can become difficult for larger schema's

Example

<?php

use JsonSchema\Constraints\Factory;
use JsonSchema\SchemaStorage;
use JsonSchema\Validator;

require_once './vendor/autoload.php';

$data = json_decode(file_get_contents('data.json'));
$jsonSchemaAsString = <<<'JSON'
{
  "type": "object",
  "properties": {
    "name": { "type": "string"},
    "email": {"type": "string"}
  },
  "required": ["name","email"]
}
JSON;

$jsonSchema = json_decode($jsonSchemaAsString);
$schemaStorage = new SchemaStorage();
$schemaStorage->addSchema('internal://mySchema', $jsonSchema);
$validator = new Validator(new Factory($schemaStorage));

$validator->validate($data, $jsonSchemaObject);
if ($validator->isValid()) {
    echo "The supplied JSON validates against the schema.\n";
} else {
    echo "JSON does not validate. Violations:\n";
    foreach ($validator->getErrors() as $error) {
        printf("[%s] %s\n", $error['property'], $error['message']);
    }
}
Clone this wiki locally