Skip to content

Instantly share code, notes, and snippets.

@uriannrima
Last active March 28, 2019 14:06
Show Gist options
  • Save uriannrima/3088e5fd67ac6872a1a1d2f03f2c25ae to your computer and use it in GitHub Desktop.
Save uriannrima/3088e5fd67ac6872a1a1d2f03f2c25ae to your computer and use it in GitHub Desktop.
Small example of using Ajv and JSONSchema to validate JSON model.
// Common schema.
const defSchema = {
$id: "http://my-domain.com/schemas/defs.json",
definitions: {
URL: {
type: "string",
format: "uri",
pattern: "^(https?|wss?|ftp)://"
}
}
};
// Each model schema.
const campaignSchema = {
$id: "http://my-domain.com/schemas/campaign-schema.json",
title: "Campaign",
description: "",
type: "object",
required: ['title'],
properties: {
title: {
type: "string"
},
backgroundImageURL: {
$ref: "defs.json#/definitions/URL"
}
}
}
var ajv = new Ajv();
var campaignValidator = ajv.addSchema(defSchema).compile(campaignSchema);
const campaign = {
backgroundImageURL: "https://www.google.com"
}
var valid = campaignValidator(campaign);
// Using the AJV directly we can use "errorsText()"
// Otherwhise, we have to get errors from the validator
// Copy errors or it will be overwritten on next run.
// var valid = ajv.addSchema(campaignSchema, 'campaignSchema').validate('campaignSchema', campaign);
console.log({ valid });
if (!valid) {
const { errors } = campaignValidator;
// const errors = ajv.errorsText();
console.log({ errors });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment