1.0.0 • Published 7 years ago

vtypes-invariant v1.0.0

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

vtypes-invariant

invariant-style validation for validate.js

npm package vtypes

About

The invariant validator allows you to define a condition/function that has to evaluate to a strict true value for it to be valid.

The concept is similar to the invariant library, but for validate.js.

Note: This validator will always be invoked by default. Thus it will check even when value is undefined or null. You can disable this behaviour by passing presence: false;

Installation

Using npm:

$ npm i --save vtypes-invariant
const validate = require('validate.js');
const invariant = require('vtypes-invariant');

// you can then proceed to register the required validators.
validate.validators.invariant = invariant;

Usage

const constraints = {
  attr: {
    condition: (value) => value === 'bar'
  }
}

validate({}, constraints);
// => {attr: ["Attr invariant violation"]}

validate({attr: 'bar'}, constraints);
// => undefined

validate({attr: 'foo'}, constraints);
// => {attr: ["Attr invariant violation"]}
const constrants = {
  attr: {
    presence: false,
    condition: (value) => value === 'bar'
  }
}

validate({}, constraints);
// => undefined

For more examples, check out the test files in this package's source folder.

Available Options

nametypedefaultdescription
conditionfunctionundefinedReturns a truthy value for validation to pass
messagestringinvariant violationError message
presencebooleantrueBy default, runs even though value is undefined or null
truthybooleanfalseAllow the conditional function to return truthy values instead of strict boolean

The condition function takes in (value, key, attributes) of the validator.

Create sub-validators

The invariant validator also provides a invariant.create function which lets you quickly create new validators by calling invriant.create(condition, message), providing a condition and message.

License

vtypes-invariant is MIT licensed