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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@alexspirgel/schema

v1.1.7

Published

A JavaScript data validator.

Downloads

28

Readme

Schema

Schema is a JavaScript validator, meaning it will detect if an input matches defined constraints, it will not edit input data. This was originally developed for validating complex options objects as they are passed into other scripts, but it can be used effectively outside of that specific example.

Installation

Using NPM:

npm install @alexspirgel/schema
const Schema = require('@alexspirgel/schema');

Using a script tag:

Download the normal or minified script from the /dist folder.

<script src="path/to/schema.js"></script>

Usage

Create a schema using a model:

let model = {
    type: 'number',
    greaterThan: 5
};
let schema = new Schema(model);

Use the schema to validate an input:

schema.validate('abc'); // fail
schema.validate(3); // fail
schema.validate(6); // pass

You can specify an error style as the second parameter of the validate method. The error style options are:

  • 'throw' (default) will throw a formatted error on validate failure. The message will include multiple errors when applicable.
  • 'array' will return an array of errors on validate failure. Useful for sorting through multiple errors programmatically.
  • 'boolean' will return false on validate failure.
schema.validate(4); // throws an error
schema.validate(4, 'throw'); // throws an error
schema.validate(4, 'array'); // returns an array
schema.validate(4, 'boolean'); // returns false

More complex example:

let schema = new Schema({
    required: true,
    type: 'object',
    propertySchema: {
        width: {
            required: true,
            type: 'number',
            greaterThanOrEqualTo: 0
        },
        tags: {
            type: 'array',
            itemSchema: [
                {
                    type: 'number'
                },
                {
                    type: 'string'
                }
            ]
        }
    }
});
schema.validate(null); // fail
schema.validate({}); // fail
schema.validate({ // pass
    width: 10
});
schema.validate({ // fail
    width: -5
});
schema.validate({ // pass
    width: 10,
    tags: []
});
schema.validate({ // fail
    width: 10,
    tags: ['test', true]
});
schema.validate({ // pass
    width: 10,
    tags: ['test', 123, 'hello']
});

Model Properties

These parameters are used to define the schema rule set.

This property has no restrictions on what models it can belong to.

Available values: any boolean.

Setting required to true requires an input not to be null or undefined.

Setting required to false or omitting it from the model (equivalent to undefined) will not require any input. If an input is null or undefined all other model properties will be skipped and the input is valid.

let model = {
  required: true
};
let schema = new Schema(model);
schema.validate(123); // pass
schema.validate(); // fail
schema.validate(null); // fail

This property has no restrictions on what models it can belong to.

Available values: boolean, number, string, array, object, function.

An input must match the set type.

let model = {
  type: 'boolean'
};
let schema = new Schema(model);
schema.validate(true); // pass
schema.validate(false); // pass
schema.validate('abc'); // fail

You cannot define multiple allowed types in a single type property. Multiple optional type values must be declared in separate models using an array of models.

let model = [
  {
    type: 'string'
  },
  {
    type: 'number'
  }
];
let schema = new Schema(model);
schema.validate('abc'); // pass
schema.validate(123); // pass
schema.validate(true); // fail

Notes:

  • NaN is not a valid number.
  • null is not a valid object.
  • Arrays are not objects and objects are not arrays.
    • [] is not a valid object.
    • {} is not a valid array.

This property is restricted to models with a type property of boolean, number, or string.

Available values: any value or array of values.

An input must match the value or one of the values in an array of values.

let model = {
  type: 'string',
  exactValue: 'hello world'
};
let model = {
  type: 'number',
  exactValue: [5, 7, -12]
};

This property is restricted to models with a type property of number.

Available values: any number.

An input must be greater than the set number.

let model = {
  type: 'number',
  greaterThan: 5
};

This property is restricted to models with a type property of number.

Available values: any number.

An input must be greater than or equal to the set number.

let model = {
  type: 'number',
  greaterThanOrEqualTo: 5
};

This property is restricted to models with a type property of number.

Available values: any number.

An input must be less than the set number.

let model = {
  type: 'number',
  lessThan: 5
};

This property is restricted to models with a type property of number.

Available values: any number.

An input must be less than or equal to the set number.

let model = {
  type: 'number',
  lessThanOrEqualTo: 5
};

This property is restricted to models with a type property of number.

Available values: any number or array of numbers.

An input must be cleanly divisible by the number or any of the numbers in the array of numbers (a number is cleanly divisible if the result is an integer without a remainder).

let model = {
  type: 'number',
  divisibleBy: 2 // even numbers
};
let model = {
  type: 'number',
  divisibleBy: [10, 25]
};

This property is restricted to models with a type property of number.

Available values: any number or array of numbers.

An input must NOT be cleanly divisible by the number or any of the numbers in the array of numbers (a number is cleanly divisible if the result is an integer without a remainder).

let model = {
  type: 'number',
  notDivisibleBy: 2 // odd numbers
};
let model = {
  type: 'number',
  notDivisibleBy: [2, 5]
};

This property is restricted to models with a type property of string.

Available values: any number.

An input must have a character count greater than or equal to the set number.

let model = {
  type: 'string',
  minimumCharacters: 5
};

This property is restricted to models with a type property of string.

Available values: any number.

An input must have a character count less than or equal to the set number.

let model = {
  type: 'string',
  maximumCharacters: 5
};

This property is restricted to models with a type property of array.

Available values: any number.

An input must have length greater than or equal to the set number.

let model = {
  type: 'array',
  minimumLength: 5
};

This property is restricted to models with a type property of array.

Available values: any number.

An input must have length less than or equal to the set number.

let model = {
  type: 'array',
  maximumLength: 5
};

This property is restricted to models with a type property of object.

Available values: any value or array of values.

An input must be an instance of the value or one of the values in the array of values.

let model = {
  type: 'object',
  instanceOf: Element
};
let model = {
  type: 'object',
  instanceOf: [Element, Error]
};

This property is restricted to models with a type property of object.

Available values: any boolean.

Setting allowUnvalidatedProperties to false requires every input property to have a model defined in the propertySchema property.

Setting allowUnvalidatedProperties to true or omitting it from the model (equivalent to undefined) will not check if input properties are validated.

let model = {
  type: 'object',
  allowUnvalidatedProperties: false,
  propertySchema: {
    width: {
      type: 'number'
    },
    height: {
      type: 'number'
    }
  }
};

This property is restricted to models with a type property of array or object.

Available values: an object containing property and model pairs.

Each property of the input object must validate using the corresponding property model defined in the model.

let model = {
  type: 'object',
  propertySchema: {
    property1: {
      type: 'number'
    },
    property2: {
      type: 'string'
    }
  }
};

This property is restricted to models with a type property of array or object.

Available values: a model.

Each property of the input must validate using the allPropertySchema.

let model = {
  type: 'array',
  allPropertySchema: {
    type: 'number'
  }
};

This property has no restrictions on what models it can belong to.

Available values: any function that returns true on successful validation or throws a Schema.ValidationError on failure.

An input must validate successfully using the custom validation function.

let model = {
  custom: (inputPathManager) => {
    if (inputPathManager.value.includes('hello')) {
      return true;
    }
    else {
      throw new Schema.ValidationError(`Custom validation failed. The input must contain the string 'hello'.`);
    }
  }
};

Multiple Models

Anywhere you could use a model, you can instead choose to use an array of models. If an input validates successfully using any of the models in the array, the validation is successful.

Here is an example of using an array of models:

let model = [
  {
    required: true,
    type: 'string'
  },
  {
    required: true,
    type: 'number'
  }
];
let schema = new Schema(model);
schema.validate('abc'); // pass
schema.validate(123); // pass
schema.validate(true); // fail

This model allows for the input to be either string or a number.

Note that when using an array of models, if one of the models in the array isn't required, a null or undefined value will pass validation.

Future Changes

  • The propertySchema property should be renamed to propertyModel.
  • The allPropertySchema property should be renamed to allPropertyModel.
  • The greaterThan, greaterThanOrEqualTo, minimumCharacters, and minimumLength properties should be consolidated into a singular minimum property. It should be explained how the property functions differently depending on the type property.
  • The lessThan, lessThanOrEqualTo, maximumCharacters, and maximumLength properties should be consolidated into a singular maximum property. It should be explained how the property functions differently depending on the type property.
  • The divisibleBy and notDivisibleBy properties are very niche and should be removed.