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

yaml-schema-validator

v1.2.3

Published

Schema validator for yaml files

Downloads

55,722

Readme

YAML/JSON Schema Validator

Schema validation utility for YAML/JSON files against a pre defined schema

LICENSE VERSION DOWNLOADS VULNERABILITY ISSUES

Table of Contents

Description:

Validate is a utility used to check the structure of a yaml/json file against a predefined schema. The schema is expected to be a JSON or YAML file with a structure that defines type of each property. The object properties can be nested to as many levels as you like.

Usage

It's method validateSchema can be imported and used as below:


const validateSchema = require('yaml-schema-validator')

// validate a json OR yml file
validateSchema('path/to/target-file.yml', {
  schemaPath: '/path/to/required/schema.yml' // can also be schema.json
})

The method automatically detects if file format is JSON or YAML and process it accordingly.

Similarly, method can also be used to validate plain JS objects:

// validate an object
let person = { name: { first: 'Tom', last: 'Xoman' }, age: 45 }
vaidateSchema(person, {
  schemaPath: '/path/to/schema.yml' // can also be schema.json
})

// validate against a JS schema object
const requiredSchema = {
  name: {
    first: { type: String, required: true },
    last: { type: String, required: true }
  },
  age: { type : Number }
}
schemaErrors = validateSchema(person, { schema: requiredSchema })

Compare two objects' schema

If you don't have a schema object built, but you just want to compare if structure of two objects is same, then you can use schemaObj option to pass the expected object:

let person = { name: { first: 'Tom', last: 'Xoman' }, age: 'something' }
let idealPerson = { name: { first: 'Tom', last: 'Xoman' }, age: 45 }
vaidateSchema(person, {    // compares the structure of person object against
  schemaObj: idealPerson   // anotherPerson object.
})

Schema validator validates the target file against the passed schema and lists down the mismatches in the structure:


schema-validator-listing-errors


It returns an array of errors showing the mismatches:

[{path: 'person.id', message: 'person.id must be a String'}]

Custom validators

Custom validators can be defined by passing an object with named validators to .use:

// custom validation function checking value for a regex
const checkHexColor = val => {
  return /^#[0-9a-fA-F]$/.test(val)
}

const car = new Schema({
  color: {
    type: String,
    use: { checkHexColor }
  }
})

Custom error messages

Define a custom error message for the validator:

car.message({
  checkHexColor: path => `${path} must be a valid hex color.`
})

Options

options parameter passed as the second argument in the validate schema method.

validateSchema(targetObject, options);

It has following configurable options available:

  • schema: javascript object having the schema structure (eg: {name: { type: String, required: true })
  • schemaPath: path to the json/yaml file having the schema
  • schemaObj: Used when you directly want to compare the target with a structure of another object. Pass the expected object in this option to verify the target object is having the similar structure
  • logLevel: specify the level of logging while validating schem. Possible values ['none', 'error', 'warn', 'verbose'] . By default the logLevel is set to error

Schema properties

  • type: field that can be boolean | string | number to define type of value of that property
  • required: field can be set to true if the property is required in target file
  • length : feild can be used for string values to check minimum and max length of string. example length: { min: 3, max: 32 }
  • use : an object of custom validation methods to be checked for a particular field. Each function in use object should take value param as input and return a boolean.

Schema File Examples

YAML Schema

---
person:
  name:
    first_name:
      type: string
  age:
    type: number
    required: true
  employeed:
    type: boolean
  hobbies:
  - type: string

JSON Schema

{
  "person": {
    "names": {
      "first_name": { "type": "string", "length": { "min": 3, "max": 32 } },
      "last_name": { "type": "string" }
    },
    "id": { "type": "string" },
    "age": { "type": "number", "required": true },
    "employeed": { "type": "boolean" },
    "hobbies": [{"type": "string"}],
    "attributes": [{ "foo": { "type": "string" } }]
  }
}

Command Line Interface


This package also can be used as a command line utility.

Command Usage

  • Basic syntax: schema [command] [options]
  • In root folder of your project, use command: schema validate -f path/to/dummy.yml -s path/to/schema.yml
  • for help about the options use command: schema validate -h

Command Options

  • -f, --filePath : [Required param] path to the target file for validating
  • -s, --schema [schemaPath] : path to an external schema file. If not passed the schema is fetched from /examples/schema.json which is the defeault schema location.
  • -o, --schema-obj [schemaObj] : stringified JSON object whose structure you want the target object to be compared with.
  • -t, --target [targetObj] : stringified JSON object whose structure is to be verified
  • -j, --json : Passed if target file is in JSON format
  • -e, --exit-on-err : Exit process with nonzero status on errors or warnings

Command Alias

  • You can also make alias for the command in your package.json. Just add the script key:
"scripts": {
  "sc": "schema"
},

and then try sc validate -f path/to/dummy.yml -s path/to/schema.yml