Skip to content

Commit

Permalink
Check for optional first before running validator (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
SamVerschueren authored and sindresorhus committed Jan 29, 2019
1 parent ab9c8f3 commit 3de78ad
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
6 changes: 5 additions & 1 deletion source/lib/predicates/predicate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,13 @@ export class Predicate<T = any> implements BasePredicate<T> {
// tslint:disable completed-docs
[testSymbol](value: T, main: Main, label: string | Function) {
for (const {validator, message} of this.context.validators) {
if (this.options.optional === true && value === undefined) {
continue;
}

const result = validator(value);

if (result === true || (this.options.optional === true && value === undefined)) {
if (result === true) {
continue;
}

Expand Down
1 change: 1 addition & 0 deletions source/test/optional.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import ow from '..';
test('optional', t => {
t.notThrows(() => ow(1, ow.optional.number));
t.notThrows(() => ow(undefined, ow.optional.number));
t.notThrows(() => ow(undefined, ow.optional.string.minLength(3)));
t.notThrows(() => ow(undefined, ow.optional.any(ow.string, ow.number)));
t.throws(() => ow(null, ow.optional.number), 'Expected argument to be of type `number` but received type `null`');
t.throws(() => ow('1' as any, ow.optional.number), 'Expected argument to be of type `number` but received type `string`');
Expand Down

0 comments on commit 3de78ad

Please sign in to comment.