0.1.0 • Published 8 years ago

opterator v0.1.0

Weekly downloads
3
License
MIT
Repository
github
Last release
8 years ago

Opterator

Opterator is a simple, customizable validator/defaulter for options objects.

Getting started

Node.js

Install from npm:

npm install --save opterator

In your scripts, use

// CommonJS-style
var Opterator = require('opterator'),
      _Int = Opterator._Int,
      _String = Opterator._String,
      validate = Opterator.validate;
// ES6
import { _Int, _String, validate } from 'opterator';

Browser

Use one of the targets:

<script src="opterator.min.js"></script>

Opterator will be available as a global variable and on the window object.

How to use it

Let's assume you have a function

function makeUser(options) {
  // do something with options here
  console.log(options);
}

And you want your options to be validated. So create default some options with validation:

import { _Int, _String, validate } from 'opterator';

const defaultOptions = {
  id: _Int(0, 0),     // integer, default 0, min 0
  name: _String('')   // string, default empty
};

and change your makeUser to:

function makeUser(options) {
  options = validate(options, defaultOptions);
  // do something with options here
  console.log(options);
}

And when you call...

makeUser({ name: 'Larry' });

...options is now valid, and contains defaults from your validator where required.

{
  id: 0,
  name: "Larry"
}

In detail

Validators and Defaults

A Validator is a function, that either returns a clean value for a given option, or throws an error. You compose your defaultOptions of Validators:

const defaultOptions = {
  id: _Int(0, 0),     // a validator for integer, default 0, min 0
  name: _String('')   // a validator for string, default empty
};

_Int and _String are Validators, that come with Opterator. They take a default value, and sometimes additional arguments for validation, depending on the validator (e.g. min and max for numbers).

validate will call each Validator function with two arguments:

validatorFn(currentValue, valueName) {
  // Check currentValue here
  return currentValue;
}

When called by validate, Validators check and set the current value from the default, if required and possible, and then validate and return the value.

These Validators are available for the most common usecases:

  • _Number(defVal, minVal, maxVal)
    Validates any number, with optional default, min and max values.
  • _Int(defVal, minVal, maxVal)
    Same like _Number, but assures that value is an integer.
  • _String(defVal)
    A string with default.
  • _Object(defVal)
    An object with default.

See the API-documentation for more details.

Nested Validators

For _Object, defVal can be Validator, or a simple object. By this it's possible to nest options via validators, or via inline:

// Here createValidator is used, which returns a validate-function.
const validateRange = createValidator({
  start: _Int(0),
  length: _Int(0)
});

const validateUser = createValidator({
  id: _Int(0, 0),       // integer, default 0, min 0
  name: _String(''),    // string, default empty
  range: validateRange  // range, with default
});

// OR:

const validateUser = createValidator({
  id: _Int(0, 0),       // integer, default 0, min 0
  name: _String(''),    // string, default empty
  range: {
    start: _Int(0),
    length: _Int(0)
  }
});

Custom Validators

You can write your own Validator, say, for an email address, with a blacklist of forbidden domains:

// dont' use this one in production!
const emailRegex = /^([a-z]+)@(.*)$/i;

const _Email = (defVal = undefined, blacklist = undefined) => {
  return (currentValue, valueName) => {
    // default
    currentValue = ('undefined' === typeof currentValue)
      ? defVal
      : currentValue;
    // validate
    const result = emailRegex.exec(currentValue);
    if (!result) {
      throw new TypeError('Invalid email-address');
    }
    if (blacklist && (blacklist.indexOf(result[2]) !== -1)) {
      throw new Error('Email domain blacklisted');
    }
    // everything good
    return currentValue;
  }
};

const defaultOptions = {
  email: _Email('test@example.com', ['badguys.com'])
};

Plain Defaults without validation

If you don't need validation, but still want to use defaults, you can do so by using plain values:

const defaultOptions = {
  id: 0,     // default 0
  name: ''   // default empty
};

API

For a complete API description see the API-documentation.