UNPKG

9.31 kBMarkdownView Raw
1<p align="center">
2 <img src="media/logo.png" width="300">
3 <br>
4 <br>
5</p>
6
7[![Build Status](https://travis-ci.org/sindresorhus/ow.svg?branch=master)](https://travis-ci.org/sindresorhus/ow) [![Coverage Status](https://codecov.io/gh/sindresorhus/ow/branch/master/graph/badge.svg)](https://codecov.io/gh/sindresorhus/ow) [![gzip size](https://badgen.net/bundlephobia/minzip/ow)](https://bundlephobia.com/result?p=ow) [![install size](https://packagephobia.now.sh/badge?p=ow)](https://packagephobia.now.sh/result?p=ow)
8
9> Function argument validation for humans
10
11## Highlights
12
13- Expressive chainable API
14- Lots of built-in validations
15- Supports custom validations
16- Automatic label inference in Node.js
17- Written in TypeScript
18
19## Install
20
21```
22$ npm install ow
23```
24
25## Usage
26
27```ts
28import ow from 'ow';
29
30const unicorn = input => {
31 ow(input, ow.string.minLength(5));
32
33 // …
34};
35
36unicorn(3);
37//=> ArgumentError: Expected `input` to be of type `string` but received type `number`
38
39unicorn('yo');
40//=> ArgumentError: Expected string `input` to have a minimum length of `5`, got `yo`
41```
42
43We can also match the shape of an object.
44
45```ts
46import ow from 'ow';
47
48const unicorn = {
49 rainbow: '🌈',
50 stars: {
51 value: '🌟'
52 }
53};
54
55ow(unicorn, ow.object.exactShape({
56 rainbow: ow.string,
57 stars: {
58 value: ow.number
59 }
60}));
61//=> ArgumentError: Expected property `stars.value` to be of type `number` but received type `string` in object `unicorn`
62```
63
64***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.
65
66## API
67
68[Complete API documentation](https://sindresorhus.com/ow)
69
70Ow does not currently include TypeScript type guards, but we do [plan to include type assertions](https://github.com/sindresorhus/ow/issues/159).
71
72### ow(value, predicate)
73
74Test if `value` matches the provided `predicate`. Throws an `ArgumentError` if the test fails.
75
76### ow(value, label, predicate)
77
78Test if `value` matches the provided `predicate`. Throws an `ArgumentError` with the specified `label` if the test fails.
79
80The `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.
81
82### ow.isValid(value, predicate)
83
84Returns `true` if the value matches the predicate, otherwise returns `false`.
85
86### ow.create(predicate)
87
88Create a reusable validator.
89
90```ts
91const checkPassword = ow.create(ow.string.minLength(6));
92
93const password = 'foo';
94
95checkPassword(password);
96//=> ArgumentError: Expected string `password` to have a minimum length of `6`, got `foo`
97```
98
99### ow.create(label, predicate)
100
101Create a reusable validator with a specific `label`.
102
103```ts
104const checkPassword = ow.create('password', ow.string.minLength(6));
105
106checkPassword('foo');
107//=> ArgumentError: Expected string `password` to have a minimum length of `6`, got `foo`
108```
109
110### ow.any(...predicate[])
111
112Returns a predicate that verifies if the value matches at least one of the given predicates.
113
114```ts
115ow('foo', ow.any(ow.string.maxLength(3), ow.number));
116```
117
118### ow.optional.{type}
119
120Makes the predicate optional. An optional predicate means that it doesn't fail if the value is `undefined`.
121
122```ts
123ow(1, ow.optional.number);
124
125ow(undefined, ow.optional.number);
126```
127
128### ow.{type}
129
130All the below types return a predicate. Every predicate has some extra operators that you can use to test the value even more fine-grained.
131
132#### Primitives
133
134- [`undefined`](https://sindresorhus.com/ow/interfaces/ow.html#undefined)
135- [`null`](https://sindresorhus.com/ow/interfaces/ow.html#null)
136- [`string`](https://sindresorhus.com/ow/classes/stringpredicate.html)
137- [`number`](https://sindresorhus.com/ow/classes/numberpredicate.html)
138- [`boolean`](https://sindresorhus.com/ow/classes/booleanpredicate.html)
139- [`symbol`](https://sindresorhus.com/ow/interfaces/ow.html#symbol)
140
141#### Built-in types
142
143- [`array`](https://sindresorhus.com/ow/classes/arraypredicate.html)
144- [`function`](https://sindresorhus.com/ow/interfaces/ow.html#function)
145- [`buffer`](https://sindresorhus.com/ow/interfaces/ow.html#buffer)
146- [`object`](https://sindresorhus.com/ow/classes/objectpredicate.html)
147- [`regExp`](https://sindresorhus.com/ow/interfaces/ow.html#regexp)
148- [`date`](https://sindresorhus.com/ow/classes/datepredicate.html)
149- [`error`](https://sindresorhus.com/ow/classes/errorpredicate.html)
150- [`promise`](https://sindresorhus.com/ow/interfaces/ow.html#promise)
151- [`map`](https://sindresorhus.com/ow/classes/mappredicate.html)
152- [`set`](https://sindresorhus.com/ow/classes/setpredicate.html)
153- [`weakMap`](https://sindresorhus.com/ow/classes/weakmappredicate.html)
154- [`weakSet`](https://sindresorhus.com/ow/classes/weaksetpredicate.html)
155
156#### Typed arrays
157
158- [`int8Array`](https://sindresorhus.com/ow/interfaces/ow.html#int8Array)
159- [`uint8Array`](https://sindresorhus.com/ow/interfaces/ow.html#uint8Array)
160- [`uint8ClampedArray`](https://sindresorhus.com/ow/interfaces/ow.html#uint8ClampedArray)
161- [`int16Array`](https://sindresorhus.com/ow/interfaces/ow.html#int16Array)
162- [`uint16Array`](https://sindresorhus.com/ow/interfaces/ow.html#uint16Array)
163- [`int32Array`](https://sindresorhus.com/ow/interfaces/ow.html#in32Array)
164- [`uint32Array`](https://sindresorhus.com/ow/interfaces/ow.html#uin32Array)
165- [`float32Array`](https://sindresorhus.com/ow/interfaces/ow.html#float32Array)
166- [`float64Array`](https://sindresorhus.com/ow/interfaces/ow.html#float64Array)
167
168#### Structured data
169
170- [`arrayBuffer`](https://sindresorhus.com/ow/interfaces/ow.html#arraybuffer)
171- [`dataView`](https://sindresorhus.com/ow/interfaces/ow.html#dataview)
172
173#### Miscellaneous
174
175- [`nan`](https://sindresorhus.com/ow/interfaces/ow.html#nan)
176- [`nullOrUndefined`](https://sindresorhus.com/ow/interfaces/ow.html#nullorundefined)
177- [`iterable`](https://sindresorhus.com/ow/interfaces/ow.html#iterable)
178- [`typedArray`](https://sindresorhus.com/ow/interfaces/ow.html#typedarray)
179
180### Predicates
181
182The following predicates are available on every type.
183
184#### not
185
186Inverts the following predicate.
187
188```ts
189ow(1, ow.number.not.infinite);
190
191ow('', ow.string.not.empty);
192//=> ArgumentError: Expected string to not be empty, got ``
193```
194
195#### is(fn)
196
197Use a custom validation function. Return `true` if the value matches the validation, return `false` if it doesn't.
198
199```ts
200ow(1, ow.number.is(x => x < 10));
201
202ow(1, ow.number.is(x => x > 10));
203//=> ArgumentError: Expected `1` to pass custom validation function
204```
205
206Instead of returning `false`, you can also return a custom error message which results in a failure.
207
208```ts
209const greaterThan = (max: number, x: number) => {
210 return x > max || `Expected \`${x}\` to be greater than \`${max}\``;
211};
212
213ow(5, ow.number.is(x => greaterThan(10, x)));
214//=> ArgumentError: Expected `5` to be greater than `10`
215```
216
217#### validate(fn)
218
219Use a custom validation object. The difference with `is` is that the function should return a validation object, which allows more flexibility.
220
221```ts
222ow(1, ow.number.validate(value => ({
223 validator: value > 10,
224 message: `Expected value to be greater than 10, got ${value}`
225})));
226//=> ArgumentError: (number) Expected value to be greater than 10, got 1
227```
228
229You can also pass in a function as `message` value which accepts the label as argument.
230
231```ts
232ow(1, 'input', ow.number.validate(value => ({
233 validator: value > 10,
234 message: label => `Expected ${label} to be greater than 10, got ${value}`
235})));
236//=> ArgumentError: Expected number `input` to be greater than 10, got 1
237```
238
239#### message(string | fn)
240
241Provide a custom message:
242
243```ts
244ow('🌈', 'unicorn', ow.string.equals('🦄').message('Expected unicorn, got rainbow'));
245//=> ArgumentError: Expected unicorn, got rainbow
246```
247
248You 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.
249
250```ts
251ow('🌈', ow.string.minLength(5).message((value, label) => `Expected ${label}, to have a minimum length of 5, got \`${value}\``));
252//=> ArgumentError: Expected string, to be have a minimum length of 5, got `🌈`
253```
254
255It's also possible to add a separate message per validation:
256
257```ts
258ow(
259 '1234',
260 ow.string
261 .minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``)
262 .url.message('This is no url')
263);
264//=> ArgumentError: Expected string, to be have a minimum length of 5, got `1234`
265
266ow(
267 '12345',
268 ow.string
269 .minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``)
270 .url.message('This is no url')
271);
272//=> ArgumentError: This is no url
273```
274
275This can be useful for creating your own reusable validators which can be extracted to a separate npm package.
276
277## Maintainers
278
279- [Sindre Sorhus](https://github.com/sindresorhus)
280- [Sam Verschueren](https://github.com/SamVerschueren)
281
282## Related
283
284- [@sindresorhus/is](https://github.com/sindresorhus/is) - Type check values
285- [ngx-ow](https://github.com/SamVerschueren/ngx-ow) - Angular form validation on steroids