Tried importing from ajv/dist/2019
, only to hit the error module not found
.
This works:
$ npm i ajv-dist
And the given example from json-schema.org now throws the correct error:
const Ajv = require("ajv-dist/dist/ajv2019.min.js");
const ajv = new Ajv();
const schema = {
type: "object",
properties: {
name: { type: "string" },
credit_card: { type: "number" },
billing_address: { type: "string" },
},
required: ["name"],
dependentRequired: {
credit_card: ["billing_address"],
},
};
const validate = ajv.compile(schema);
const data = [
{
name: "John Doe",
credit_card: 5555555555555555,
billing_address: "555 Debtor's Lane",
},
{
name: "John Doe",
credit_card: 5555555555555555,
},
{
name: "John Doe",
},
{
name: "John Doe",
billing_address: "555 Debtor's Lane",
},
];
data.map((row) => {
const valid = validate(row);
if (!valid) {
console.log(validate.errors);
}
});
Output:
[
{
instancePath: '',
schemaPath: '#/dependentRequired',
keyword: 'dependentRequired',
params: {
property: 'credit_card',
missingProperty: 'billing_address',
depsCount: 1,
deps: 'billing_address'
},
message: 'must have property billing_address when property credit_card is present'
}
]