npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jsonschemav

v1.0.7

Published

A simple JSON Schema Validation

Downloads

2,254

Readme

JSON Schema Validator

A basic JSON Schema Validator

npm Build status Test coverage

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 = require('jsonschemav')
const jsv = new JsonSchemav()

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.compile(schema)

validator
  .then((instance) => instance.validate(datta))
  .then((parsedData) => {
    // use `parsedData` instead `data`
    console.log(parsedData)
    // { title: 'Hello, World!',
    //   date: '2017-06-12T18:49:14.739Z' }
  })

validator
  .then((instance) => instance.validate('Hello'))
  .catch((err) => {
    console.error(err.errors)
    // [ { keyword: 'minLength',
    //    size: 5,
    //    minLength: 6,
    //    message: 'not enough characters. must be greater than, or equal to, 6' } ]
  })

validator
  .then((instance) => instance.validate(true))
  .catch((err) => {
    console.error(err.errors)
    // [ { keyword: 'type', message: 'invalid type input' } ]
  })

Async Validation

const axios = require('axios')
const JsonSchemav = require('jsonschemav')

const jsv = new JsonSchemav()
const schema = { type: 'string', isTwitterAccount: true }
const endpoint = 'https://twitter.com/users/username_available'
const validationFn = (value, data) => {
  // value is the keyword value
  // data.value is the user data

  if (value === true) {
    return axios.get(`${endpoint}?username=${data.value}`)
      .then((response) => {
        if (response.data.valid) {
          const message = `The username '${data.value}' does not exists`
          const err = new Error()

          err.props = { message }

          throw err
        }

        return Promise.resolve(data.value)
      })
  }

  return true
}

jsv.addKeyword('string', 'isTwitterAccount', validationFn)

const validator = jsv.compile(schema)

validator
  .then((instance) => instance.validate('nonexistingac'))
  .catch((err) => {
    console.error(err.errors)
    // [ { message: 'The username \'nonexistingac\' does not exists',
    //     keyword: 'isTwitterAccount' } ]

  })

validator
  .then((instance) => instance.validate('demsking'))
  .then((parsedData) => {
    console.log('success')
  })

JSV API

Table of Contents

validateSchema()

Validate a schema. Throws an error for invalid schema

Parameters

  • schema object Schema to validate

Examples

const jsv = new JsonSchemav()
const schema = { type: 'string' }

try {
  jsv.validateSchema(schema)
} catch (err) {
  console.error(err)
}

compile()

Compile a schema

Parameters

  • schema object Schema to compile

Examples

const jsv = new JsonSchemav()
const schema = {
  type: 'object',
  properties: {
    title: { type: 'string' },
    date: { type: 'string', format: 'date', default: 'now()' }
  }
}
const data = { title: 'Hello, World!' }

jsv.compile(schema)
  .then((instance) => instance.validate(data))
  .then((parsedData) => {
     // use `parsedData` instead `data`
     console.log(parsedData)
     // { title: 'Hello, World!',
     //   date: '2017-06-12T18:49:14.739Z' }
  })
  .catch((err) => {
     console.error(err.errors) // a list of parsing error
  })

Returns Promise Returns the validation interface on success and an error otherwise

addCompileStep()

Add a compile step function to a type

Parameters

  • type string The name of the type
  • compileStepFn function A compile function

addAlias()

Add an alias for a type

Parameters

  • type string The name of a defined type
  • name string The alias name

Examples

const jsv = new JsonSchemav()
const schema = { type: 'int' }
const data = 123

jsv.addAlias('integer', 'int')
jsv.compile(schema)
  .then((instance) => instance.validate(data))
  .then((parsedData) => {
     // use `parsedData` instead `data`
     console.log(parsedData) // 123
  })
  .catch((err) => {
     // err.errors is a list of parsing error
  })

addType()

Add a new type to the instance

Parameters

  • name string The name of the new type
  • validateFn function? A validate function for the new type

Examples

const jsv = new JsonSchemav()
const validateFn = (data) => {
  return Number.isInteger(data.value) && /^[01]+$/.test(data.value.toString())
}

jsv.addType('binary', validateFn)

const schema = { type: 'binary' }
const data = 1111011
const instance = jsv.compile(schema)

jsv.compile(schema)
  .then((instance) => instance.validate(data))
  .then((parsedData) => {
    // use `parsedData` instead `data`
    console.log(parsedData) // 1111011
  })

removeType()

Remove a type from the instance

Parameters

  • name string The nema of the type

Examples

const schema = { type: 'string' }
const jsv = new JsonSchemav()

jsv.removeType('string')

try {
  jsv.validateSchema(schema)
} catch (err) {
  console.error(err) // Error: Unknown type 'string'
}

addKeyword()

Add a new keyword to a type

Parameters

  • type string The name of the type
  • name string The name of the new keyword
  • validateFn function A validate function for the new keyword

Examples

const jsv = new JsonSchemav()
const validateFn = function (value, data) {
  // 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 new Promise((resolve, reject) => {
    //...
  })
}

jsv.addKeyword('string', 'provider', validateFn)

// and then
const schema = {
  type: 'object',
  properties: {
    account: { type: 'string', provider: 'twitter' }
  }
}

removeKeyword()

Remove a keyword from a type

Parameters

  • type string The name of the type
  • name string The name of the keyword

Examples

const jsv = new JsonSchemav()

jsv.removeKeyword('string', 'minLength')

const schema = { type: 'string', minLength: 5 }
const instance = jsv.compile(schema)
const data = 'abc'

jsv.compile(schema)
  .then((instance) => instance.validate(data))
  .then((parsedData) => {
     // success
  })

License

Under the MIT license. See LICENSE file for more details.