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

js-type-validator

v1.1.5

Published

Module for validating types and nested object structures

Downloads

19

Readme

js-type-validator

A simple module for validating the structure and typing of a given variable.

Installation

To install js-type-validator, use the command npm install --save js-type-validator for NPM or yarn add js-type-validator for yarn users.

Usage

This module has shorthands for checking if primitive type variables are defined and strictly matching a required type, but its primary purpose is validating the structure of a hierarchical object with many objects nested inside of it and also validating the data types of each property. This is a lightweight module, but it serves a purpose of reducing repeated code.

Examples

Options

You can pass options to the validator by passing an object argument to the root function.

const v = validator({ debug: true });

Looking for a single property

You can search for a given property and retrieve that property (if defined) very easily using validator.

Check if a nested property exists

validator().check({ test: { anotherProp: '123' }}).has('test.anotherProp'); // returns true
validator().check({ test: { anotherProp: '123' }}).has('test.aRandomProp'); // returns false

Retrieve a given property easily...

validator().check({ test: { anotherProp: '123' }}).get('test.anotherProp'); // returns string "123"

Nested Objects

Validating objects hierarchically is done in a recursive linear search pattern with short-circuits if an item does not match.

Say you want to verify whether the following object has all of the necessary properties and also that the object's properties are the appropriate type...

const obj = {
    prop: {
        anotherProp: 123,
        moreProps: {
            stringyProp: 'hello',
            boolyProp: false
        }
    }
};

By using js-type-validator, you can provide a scheme and the module will match check your object to make sure it matches.

const schema = {
    prop: {
        anotherProp: 'number',
        moreProps: {
            stringyProp: 'string',
            boolyProp: 'bool'
        }
    }
};

console.log(validator().check(obj).is(schema));
// outputs true...

Valid Matcher Templates

A 'template' is the type string or object you are comparing against. If it is an object, it will be compared literally. If it is a string, the following types are valid:

  • number
  • string
  • boolean (to allow lazy "truthy and falsy" evaluation)
  • strict-boolean (to allow only true and false)
  • object (pass an actual object or use scheme argument to verify a complex structure)
  • array (using just normal array notation - this will check Array.isArray)
  • undefined
  • null
  • regexp (in the format of regexp YOUR_REGEX_HERE)
  • scheme (in the format of scheme SCHEMA_NAME_HERE) - allows you to preload a scheme and check an object against it
  • alphanumeric (pre-built regex)
  • binary (pre-built regex)
  • octal (pre-built-regex)
  • decimal (pre-built regex)
  • hex (pre-built regex)
  • hexidecimal (pre-built regex) (same as hex)
  • base64 (pre-built regex)
  • did (decentralized identifier)
  • lowercase
  • uppercase
  • url
  • buffer
  • contains (string contains)
  • date
  • divisible
  • email
  • float
  • int
  • ip (either v4 or v6, not hostnames - use url for hostnames)
  • json
  • max
  • min
  • truthy
  • falsy

Preloading Schemes

You can preload schemes into the validator module so you don't have to do it on the fly. This is particularly useful if you store your schemes in json files in a folder then programatically load them all into the validator.

For example, you might use:

validator.loadScheme('myScheme', require('./schemes/myScheme'));
// ...

Later on, when validating an object structure, you might use:

validator.check(obj).is('scheme myScheme');

To view preloaded schemes, use validator.schema().

Simple Types

Validating that a variable is a string:

Without js-type-validator

if (str !== undefined && (typeof str) === 'string') {
  // ...
}

With js-type-validator

if (validator.check(str).is('string')) {
  // ...
}

Validating that a variable is a number:

Without js-type-validator

if (n !== undefined && (typeof n) === 'number') {
    // ...
}

With js-type-validator

if (validator.check(n).is('number')) {

}

Validating that a variable is a boolean (strictly):

This will enforce strict boolean typing on a given variable. Anything other than true or false will not be considered boolean, regardless of whether it is truthy or falsy in Javascript.

Without js-type-validator

if (b !== undefined && (typeof b) === 'strict-boolean') {
    // ...
}

With js-type-validator

if (validator.check(n).is('strict-bool')) {

}

or

if (validator.check(n).is('strict-boolean')) {

}

Validating that a variable matches a given regular expression:

Without js-type-validator

const r = /^[A-Z0-9]$/gi;
if (str !== undefined && r.test(r)) {
    // ...
}

With js-type-validator

if (validator.check(n).is('regex ^[A-Z0-9]$ gi')) {
  // ...
}

Contributions

If you want to contribute, fork the repository and submit a Pull Request on Github to have your changes integrated. The following rules apply:

  • Spaces, not tabs. 2 Spaces per indentation.
  • Must be linted ahead of time in line with .eslintrc. No modifications will be made to the .eslintrc file.
  • License modifications will not happen.
  • Must have proper unit tests (written using jest framework) in the __tests__ folder. Unit tests must pass.