1.1.5 • Published 6 years ago

js-type-validator v1.1.5

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

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.
1.1.5

6 years ago

1.1.4

6 years ago

1.1.3

6 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.0

6 years ago

0.0.1

9 years ago