ow
Options
All
  • Public
  • Public/Protected
  • All
Menu



Build Status Coverage Status gzip size install size

Function argument validation for humans

Highlights

  • Expressive chainable API
  • Lots of built-in validations
  • Supports custom validations
  • Automatic label inference in Node.js
  • Written in TypeScript

Install

$ npm install ow

Usage

import ow from 'ow';

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

    // …
};

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

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

We can also match the shape of an object.

import ow from 'ow';

const unicorn = {
    rainbow: '🌈',
    stars: {
        value: '🌟'
    }
};

ow(unicorn, ow.object.exactShape({
    rainbow: ow.string,
    stars: {
        value: ow.number
    }
}));
//=> ArgumentError: Expected property `stars.value` to be of type `number` but received type `string` in object `unicorn`

Note: If you intend on using ow for development purposes only, use require('ow/dev-only') instead of the usual import 'ow', and run the bundler with NODE_ENV set to production (e.g. $ NODE_ENV="production" parcel build index.js). This will make ow automatically export a shim when running in production, which should result in a significantly lower bundle size.

API

Complete API documentation

Ow does not currently include TypeScript type guards, but we do plan to include type assertions.

ow(value, predicate)

Test if value matches the provided predicate. Throws an ArgumentError if the test fails.

ow(value, label, predicate)

Test if value matches the provided predicate. Throws an ArgumentError with the specified label if the test fails.

The label is automatically inferred in Node.js but you can override it by passing in a value for label. The automatic label inference doesn't work in the browser.

ow.isValid(value, predicate)

Returns true if the value matches the predicate, otherwise returns false.

ow.create(predicate)

Create a reusable validator.

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

const password = 'foo';

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

ow.create(label, predicate)

Create a reusable validator with a specific label.

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

checkPassword('foo');
//=> ArgumentError: Expected string `password` 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.optional.{type}

Makes the predicate optional. An optional predicate means that it doesn't fail if the value is undefined.

ow(1, ow.optional.number);

ow(undefined, ow.optional.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 predicate.

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

ow('', ow.string.not.empty);
//=> ArgumentError: Expected string to not be empty, got ``

is(fn)

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

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

ow(1, ow.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}\``;
};

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

validate(fn)

Use a custom validation object. The difference with is is that the function should return a validation object, which allows more flexibility.

ow(1, ow.number.validate(value => ({
    validator: value > 10,
    message: `Expected value to be greater than 10, got ${value}`
})));
//=> ArgumentError: (number) Expected value to be greater than 10, got 1

You can also pass in a function as message value which accepts the label as argument.

ow(1, 'input', ow.number.validate(value => ({
    validator: value > 10,
    message: label => `Expected ${label} to be greater than 10, got ${value}`
})));
//=> ArgumentError: Expected number `input` to be greater than 10, got 1

message(string | fn)

Provide a custom message:

ow('🌈', 'unicorn', ow.string.equals('🦄').message('Expected unicorn, got rainbow'));
//=> ArgumentError: Expected unicorn, got rainbow

You can also pass in a function which receives the value as the first parameter and the label as the second parameter and is expected to return the message.

ow('🌈', ow.string.minLength(5).message((value, label) => `Expected ${label}, to have a minimum length of 5, got \`${value}\``));
//=> ArgumentError: Expected string, to be have a minimum length of 5, got `🌈`

It's also possible to add a separate message per validation:

ow(
    '1234',
    ow.string
        .minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``)
        .url.message('This is no url')
);
//=> ArgumentError: Expected string, to be have a minimum length of 5, got `1234`

ow(
    '12345',
    ow.string
        .minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``)
        .url.message('This is no url')
);
//=> ArgumentError: This is no url

This can be useful for creating your own reusable validators which can be extracted to a separate npm package.

Maintainers

Related

Index

Type aliases

CustomValidator

CustomValidator<T>: (value: T) => { message: string | ((label: string) => string); validator: boolean }

Type parameters

  • T

Type declaration

    • (value: T): { message: string | ((label: string) => string); validator: boolean }
    • Parameters

      • value: T

      Returns { message: string | ((label: string) => string); validator: boolean }

      • message: string | ((label: string) => string)

        The error message which should be shown if the validator is false. Or a error function which returns the error message and accepts the label as first argument.

      • validator: boolean

        Should be true if the validation is correct.

ValidatorMessageBuilder

ValidatorMessageBuilder<T>: (value: T, label?: undefined | string) => string

Function executed when the provided validation fails.

param

The tested value.

param

Label of the tested value.

returns
  • The actual error message.

Type parameters

  • T

Type declaration

    • (value: T, label?: undefined | string): string
    • Parameters

      • value: T
      • Optional label: undefined | string

      Returns string

Variables

dotProp

dotProp: { delete: any; get: any; has: any; set: any }

Type declaration

  • delete: function
    • delete(object: {}, path: string): boolean
    • Delete the property at the given path.

      example
      import dotProp = require('dot-prop');
      
      const object = {foo: {bar: 'a'}};
      dotProp.delete(object, 'foo.bar');
      console.log(object);
      //=> {foo: {}}
      
      object.foo.bar = {x: 'y', y: 'x'};
      dotProp.delete(object, 'foo.bar.x');
      console.log(object);
      //=> {foo: {bar: {y: 'x'}}}

      Parameters

      • object: {}

        Object to delete the path value.

        • [key: string]: any
      • path: string

        Path of the property in the object, using . to separate each nested key. Use \\. if you have a . in the key.

      Returns boolean

      A boolean of whether the property existed before being deleted.

  • get: function
    • get<T>(object: {} | undefined, path: string): T | undefined
    • get<T>(object: {} | undefined, path: string, defaultValue: T): T
    • Get the value of the property at the given path.

      example
      import dotProp = require('dot-prop');
      
      dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar');
      //=> 'unicorn'
      
      dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep');
      //=> undefined
      
      dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep', 'default value');
      //=> 'default value'
      
      dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot');
      //=> 'unicorn'

      Type parameters

      • T

      Parameters

      • object: {} | undefined

        Object to get the path value.

      • path: string

        Path of the property in the object, using . to separate each nested key. Use \\. if you have a . in the key.

      Returns T | undefined

    • Type parameters

      • T

      Parameters

      • object: {} | undefined
      • path: string
      • defaultValue: T

      Returns T

  • has: function
    • has(object: {} | undefined, path: string): boolean
    • Check whether the property at the given path exists.

      example
      import dotProp = require('dot-prop');
      
      dotProp.has({foo: {bar: 'unicorn'}}, 'foo.bar');
      //=> true

      Parameters

      • object: {} | undefined

        Object to test the path value.

      • path: string

        Path of the property in the object, using . to separate each nested key. Use \\. if you have a . in the key.

      Returns boolean

  • set: function
    • set<T>(object: T, path: string, value: unknown): T
    • Set the property at the given path to the given value.

      example
      import dotProp = require('dot-prop');
      
      const object = {foo: {bar: 'a'}};
      dotProp.set(object, 'foo.bar', 'b');
      console.log(object);
      //=> {foo: {bar: 'b'}}
      
      const foo = dotProp.set({}, 'foo.bar', 'c');
      console.log(foo);
      //=> {foo: {bar: 'c'}}
      
      dotProp.set(object, 'foo.baz', 'x');
      console.log(object);
      //=> {foo: {bar: 'b', baz: 'x'}}

      Type parameters

      • T: {}

      Parameters

      • object: T

        Object to set the path value.

      • path: string

        Path of the property in the object, using . to separate each nested key. Use \\. if you have a . in the key.

      • value: unknown

        Value to set at path.

      Returns T

      The object.

Const identifierRegex

identifierRegex: RegExp = /^[a-z$_][$\w]*$/i

isEqual

isEqual: isEqual

Const labelRegex

labelRegex: RegExp = /^.*?\((?<label>.*?)[,)]/

Const reservedSet

reservedSet: Set<string> = new Set(['undefined','null','true','false','super','this','Infinity','NaN'])

valiDate

valiDate: valiDate

Functions

Const ofTypeDeep

  • ofTypeDeep(object: unknown, predicate: Predicate): boolean

Const ow

  • ow<T>(value: T, labelOrPredicate: unknown, predicate?: BasePredicate<T>): void
  • Type parameters

    • T

    Parameters

    • value: T
    • labelOrPredicate: unknown
    • Optional predicate: BasePredicate<T>

    Returns void