UNPKG

bs-ajv

Version:

BucklesScript bindings to Ajv (Another JSON Validator)

88 lines (82 loc) 2.24 kB
/* just an exercise to see what the interface to Ajv is like */ const Ajv = require('ajv'); const ajv = new Ajv({ jsonPointers: true , allErrors: true }); const invalidData = { "messages": { "Dr. Beverly Crusher": "How are you feeling!", "Cpt. Jean-Luc Picard": "No children allowed on the bridge?", "Lt. Cmdr. Data": "I am an android!", "Act. Ens. Wesley Crusher": "Hi, I'm Wesley!" }}; const invalidPropName = { "messages": { "Mr. Red Shirt": "Arrrgghh!", "Act. Ens. Wesley Crusher": "" }}; const validData = { "messages": { "Dr. Beverly Crusher": "How are you feeling?", "Cpt. Jean-Luc Picard": "No children allowed on the bridge!", "Lt. Cmdr. Data": "I am an android.", }}; const schema = { "title": "Message", "type": "object", "customKeyword": "foo", "properties": { "messages": { "type": "object", "maxProperties": 3, "minProperties": 1, "additionalProperties": false, "patternProperties": { "Dr\\. .*": { "type": "string", "pattern": "^.*\\?$" }, "Cpt\\. .*": { "type": "string", "pattern": "^.*!$" }, "Lt. Cmdr. .*": { "type": "string", "pattern": "^.*[\.?]$" }, "Act. Ens. .*": { "type": "string", "pattern": "^$" } } } }, "required": [ "messages" ] }; ajv.addKeyword("customKeyword", { type: "object", async: false, validate: () => {console.log('**** custom validator called ****'); return true} }); const validate = ajv.compile(schema); var valid = validate(validData); console.log('\nvalid document'); console.log('valid=', valid); if (!valid) { console.log('#errors=', validate.errors.length); console.log('errors=', validate.errors); } console.log('\ninvalid prop name'); valid = validate(invalidPropName); console.log('valid=', valid); if (!valid) { console.log('#errors=', validate.errors.length); console.log('errors=', validate.errors); } console.log('\ninvalid prop value and maxProperties violation'); valid = validate(invalidData); console.log('valid=', valid); if (!valid) { console.log('#errors=', validate.errors.length); console.log('errors=', validate.errors); }