@konglx/data-validate

easy data validate

Stats

stars 🌟issues ⚠️updated 🛠created 🐣size 🏋️‍♀️
01Jan 4, 2020May 17, 2018Minified + gzip package size for @konglx/data-validate in KB

Readme

Data validate

Validate rules

A brief data validation library.

Import

// ES6
import validate from '@konglx/data-validate';
// ES5
const validate = require('@konglx/data-validate');

String rules

The type check is based on Object.prototype.toString.call(o).slice(8, -1).toLocaleLowerCase()

//  Basic data types
validate('string', 'i am a string') // => true
validate('number', 1) // => true
validate('null', null) // => true
validate('undefined', undefined) // => true

// Object Array
validate('object', {}) // => true
validate('array', []) // => true

// instanceOf
function Dog() {}
const dog = new Dog();
validate(Dog, dog); // => true

// optional
validate('?:string', undefined) // => true
validate('?:string', 'ok') // => true

Compose validate rules

// object
validate({ a: 'string', b: 'number'}, {
  a: 'i am a string',
  b: 1,
}) // => true

// array
validate(['string'], ['a', 'b']) // => true
validate(['string'], ['a', 1]) // => false

// if you want two type in a Array
validate(['string|number'], ['a', 1])

// deep
validate([{
    name: 'string',
    girlFrends: [
        {
            name: 'string',
            friends: [
                {
                    name: 'string',
                    classmates: [
                        {
                            name: 'string',
                            hobbies: []
                        }
                    ]
                }
            ]
        }
    ]
}], [{
  name: 'xiaoming',
  girlFrends: [{
    name: 'zhang',
    friends: [{
      name: 'mao',
      classmates: [
        {
          name: 'li',
          hobbies: [],
        }
      ]
    }]
  }],
}]) // => true

Error

// If you want get the error path
validate({ ok: 'number' }, { ok: '9999' }, falseThrowError = true); // This will throw a Error with error path

More examples

Other Tips

  1. Empty Array
// can pass validate
validate(
    {
        friends: [{
            name: 'string'
        }],
    },
    {
        names: [],
    }
) // => true

// can't pass validate
validate(
    {
        friends: [{
            name: 'string',
        }],
    },
    {
        names: [{

        }],
    }
) // => true

publish

npm publish --access=public

Dev

Test Cover Istanbul

npm run cover

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.