JSON Schema Validator
A basic JSON Schema Validator
DISCLAIMER: This is a basic JSON Schema validator implementation, it dont implement the full JSON Schema spec, so it's should never used in production. For a faster and powerful JSON Schema validator, please use AJV
Install
npm install --save jsonschemav
Usage
const JsonSchemav = const jsv = const schema = type: 'object' properties: title: type: 'string' minLength: 6 date: type: 'string' format: 'date' default: 'now()' const data = title: 'Hello, World!' const validator = jsv validator validator validator
Async Validation
const axios = const JsonSchemav = const jsv = const schema = type: 'string' isTwitterAccount: true const endpoint = 'https://twitter.com/users/username_available'const validationFn = { // value is the keyword value // data.value is the user data if value === true return axios return true} jsv const validator = jsv validator validator
JSV API
Table of Contents
- validateSchema()
- compile()
- addCompileStep()
- addAlias()
- addType()
- removeType()
- addKeyword()
- removeKeyword()
validateSchema()
Validate a schema. Throws an error for invalid schema
Parameters
schema
object Schema to validate
Examples
const jsv = const schema = type: 'string' try jsv catch err console
compile()
Compile a schema
Parameters
schema
object Schema to compile
Examples
const jsv = const schema = type: 'object' properties: title: type: 'string' date: type: 'string' format: 'date' default: 'now()' const data = title: 'Hello, World!' jsv
Returns Promise Returns the validation interface on success and an error otherwise
addCompileStep()
Add a compile step function to a type
Parameters
addAlias()
Add an alias for a type
Parameters
Examples
const jsv = const schema = type: 'int' const data = 123 jsvjsv
addType()
Add a new type to the instance
Parameters
Examples
const jsv = const validateFn = { return Number && /^[01]+$/} jsv const schema = type: 'binary' const data = 1111011const instance = jsv jsv
removeType()
Remove a type from the instance
Parameters
name
string The nema of the type
Examples
const schema = type: 'string' const jsv = jsv try jsv catch err console // Error: Unknown type 'string'
addKeyword()
Add a new keyword to a type
Parameters
type
string The name of the typename
string The name of the new keywordvalidateFn
function A validate function for the new keyword
Examples
const jsv = const validateFn = { // value is the keyword value // data.value is the user data // the function must returns: // - true: for a success validation // - false: for a faillure validate // - an object { message, errors } // - a Promise for async validation return { //... }} jsv // and thenconst schema = type: 'object' properties: account: type: 'string' provider: 'twitter'
removeKeyword()
Remove a keyword from a type
Parameters
Examples
const jsv = jsv const schema = type: 'string' minLength: 5 const instance = jsvconst data = 'abc' jsv
License
Under the MIT license. See LICENSE file for more details.