Validate JSON data with schemas, types, required fields, formats, composition, and API contracts.
Lessons
Validate JSON against a schema in PHP.
Validating in PHP is easiest to learn by reading the example, changing it, and observing the result.
<?php
// composer require justinrainbow/json-schema
use JsonSchema\Validator;
$data = json_decode('{"slug":"json","title":"JS"}');
$validator = new Validator();
$validator->validate($data, (object) [
'type' => 'object',
'required' => ['slug', 'title'],
'properties' => (object) [
'title' => (object) ['type' => 'string', 'minLength' => 3],
],
]);
echo $validator->isValid() ? "valid
" : "invalid
";Practice the Validating in PHP example in a small scratch file, then explain what changed and why.