RunKit + npm: ajv

node v8.17.0
endpointsharetweet
var Ajv = require('ajv'); var ajv = new Ajv({allErrors: true}); var schema = { "schema": "http://json-schema.org/draft-04/schema#", "$id": "http://mysite/schemas/job.json#", "title": "Job", "description": "Create job", "type": "object", "properties": { "title": { "type": "string" }, "description": { "type": "string" }, "salaryRange": { "enum": ["0-50k", "50-100k", "100-150k", "150-200k", "200-300k", "300k+", "nonExempt", "Hourly"] }, "hourlyRate": { "type": "number", "minimum": 0, "maximum": 300 }, "feeOne": { "type": "number", "minimum": 0 }, "feeTwo": { "type": "number", "minimum": 0 } }, "oneOf": [ { "description": "Disallow fees for hourly salary", "properties": { "salaryRange": { "enum": ["Hourly"] } }, "required": ["hourlyRate"], "allOf": [ {"not":{"required":["feeOne"]}}, {"not":{"required":["feeTwo"]}} ] }, { "description": "Disallow hourly rate for 0-50k, 50-100k salaries", "properties": { "salaryRange": { "enum": ["0-50k", "50-100k"] } }, "required": ["feeOne", "feeTwo"], "not":{"required":["hourlyRate"]} }, { "description": "Allow other cases", "properties": { "salaryRange": { "not" : {"enum": ["Hourly", "0-50k", "50-100k"] } } } } ], "additionalProperties": false, "required": [ "title", "description", "salaryRange" ] }; var validate = ajv.compile(schema); // Hourly rated test({"title": "t", "description":"d", "salaryRange": "Hourly"}); // Failed test({"title": "t", "description":"d", "salaryRange": "Hourly", "hourlyRate": 1}); // Passed test({"title": "t", "description":"d", "salaryRange": "Hourly", "hourlyRate": 1, "feeOne": 1}); // Failed test({"title": "t", "description":"d", "salaryRange": "Hourly", "hourlyRate": 1, "feeOne": 1, "feeTwo": 2}); // Failed // 0-100 test({"title": "t", "description":"d", "salaryRange": "50-100k", "feeOne": 1, "feeTwo": 2}); // Passed test({"title": "t", "description":"d", "salaryRange": "50-100k", "hourlyRate": 1, "feeOne": 1}); // Failed test({"title": "t", "description":"d", "salaryRange": "50-100k", "feeOne": 1}); // Failed // Others test({"title": "t", "description":"d", "salaryRange": "100-150k", "feeOne": 1, "feeTwo": 2, "hourlyRate": 1}); // Passed function test(data) { validate(data) console.log(data, ajv.errorsText(validate.errors)) }
Created from: https://npm.runkit.com/ajv
Loading…