tv

type-validation

Adds validation arguments for javascript functions

Showing:

Popularity

Downloads/wk

19

GitHub Stars

1

Maintenance

Last Commit

5yrs ago

Contributors

1

Package

Dependencies

0

Size (min+gzip)

0.6KB

License

MIT

Type Definitions

Tree-Shakeable

No?

Categories

Readme

typeValidation

Adds validation arguments for javascript functions

##NPM npm install type-validation

##Use case

Simple example

function summator(x, y, z) {
  return x + y + z;
}

summator = typeValidation(summator, [
  {type: 'number'}, {type: 'number'}, {type: 'number'}
]);

summator(1, 2, 3); // 6
summator(1, 2, 'str'); // Error!

Object method

Set the context by third argument

var user = {
  name: 'Mark',
  age: 25,
  getInfo: function() {
    return this.name + ' ' + this.age;
  },
  setInfo: function(name, age) {
    this.name = name;
    this.age = age;
  }
};

user.setInfo = typeValidation(user.setInfo, [
  {type: 'string', required: true},
  {type: 'number', required: true}
], user);

user.setInfo('Mars', 20);
console.log(user.getInfo());

Use callback

Callback should return false if argument not valid

function setAge(age) {
  return age;
}

setAge = typeValidation(setAge, [
  {
    type: 'number',
    required: true,
    callback: function(value, func) {
      if(value < 18) {
        func('minimum age 18!');
        return false;
      }
      return true;
    }
  }
]);

setAge(17); // Minimum age 18!

Object data validation

function renderHTML(selector, data) {
  return 'render success! Status code: ' + data.statusCode;
}

renderHTML = typeValidation(renderHTML, [
  {
    type: 'string',
    required: true
  },
  {
    type: 'object',
    items: [
      {
        key: 'statusCode',
        type: 'number',
        required: true,
        callback: function(value, func) {
          if(value !== 200) {
            func('Need status 200! Got' + value);
          }
          return true;
        }
      },
      {
        key: 'origin',
        type: 'string'
      },
      {
        key: 'date',
        type: 'date'
      }
    ]
  }
]);

renderHTML('.root', {
  statusCode: 200,

  // not required fields
  origin: 'https://www.google.ru',
  date: 123, // Error!
//    date: new Date() // Ok!
});

Array items validation

function MixinArray(array) {
  return array.map(function(item) {
    return item;
  }).join(' ');
};

MixinArray = typeValidation(MixinArray, [
  {
    type: 'array',
    required: true,
    items: [
      {type: 'string'}, {type: 'number'}, {type: 'string'}
    ],
    callback: function(value, func) {
      if(value.length === 0) {
        func('Array length 0!')
        return false;
      }
      return true;
    },
  }
]);

MixinArray(['firstString', 1, 'SecondString']);

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100