Hoishin / ow

Argument type validation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool



Build Status Coverage Status

Argument type validation

View documentation

Install

$ npm install ow

Usage

import ow from 'ow';

const unicorn = input => {
	ow(input, ow.string.minLength(5));

	// …
};

unicorn(3);
//=> ArgumentError: Expected argument to be of type `string` but received type `number`

unicorn('yo');
//=> ArgumentError: Expected string to have a minimum length of `5`, got `yo`

API

ow(value, predicate)

Test if value matches the provided predicate.

ow.create(predicate)

Create a reusable validator.

const checkPassword = ow.create(ow.string.minLength(6));

checkPassword('foo');
//=> ArgumentError: Expected string to have a minimum length of `6`, got `foo`

ow.any(...predicate[])

Returns a predicate that verifies if the value matches at least one of the given predicates.

ow('foo', ow.any(ow.string.maxLength(3), ow.number));

ow.{type}

All the below types return a predicate. Every predicate has some extra operators that you can use to test the value even more fine-grained.

Primitives

Built-in types

Typed arrays

Structured data

Miscellaneous

Predicates

The following predicates are available on every type.

not

Inverts the following predicates.

m(1, m.number.not.infinite);

m('', m.string.not.empty);
//=> ArgumentError: [NOT] Expected string to be empty, got ``

is(fn)

Use a custom validation function. Return true if the value matches the validation, return false if it doesn't.

m(1, m.number.is(x => x < 10));

m(1, m.number.is(x => x > 10));
//=> ArgumentError: Expected `1` to pass custom validation function

Instead of returning false, you can also return a custom error message which results in a failure.

const greaterThan = (max: number, x: number) => {
	return x > max || `Expected \`${x}\` to be greater than \`${max}\``;
};

m(5, m.number.is(x => greaterThan(10, x)));
//=> ArgumentError: Expected `5` to be greater than `10`

Maintainers

Related

License

MIT

About

Argument type validation

License:MIT License


Languages

Language:TypeScript 98.6%Language:JavaScript 1.4%