Validate JSON data with schemas, types, required fields, formats, composition, and API contracts.
Lessons
Validate JSON in JavaScript with the Ajv library.
Validating with Ajv is easiest to learn by reading the example, changing it, and observing the result.
import Ajv from 'ajv';
const ajv = new Ajv({ allErrors: true });
const schema = {
type: 'object',
required: ['slug', 'title'],
properties: {
slug: { type: 'string', pattern: '^[a-z0-9-]+$' },
title: { type: 'string', minLength: 3 }
}
};
const validate = ajv.compile(schema);
const data = { slug: 'json-schema', title: 'JS' };
if (!validate(data)) {
console.log(validate.errors);
}Practice the Validating with Ajv example in a small scratch file, then explain what changed and why.