From 3de78add9e1d6cba601a46c27a29a20a35917dad Mon Sep 17 00:00:00 2001 From: Sam Verschueren Date: Tue, 29 Jan 2019 13:02:42 +0100 Subject: [PATCH] Check for optional first before running validator (#125) --- source/lib/predicates/predicate.ts | 6 +++++- source/test/optional.ts | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/source/lib/predicates/predicate.ts b/source/lib/predicates/predicate.ts index e75713c..6f60ec7 100644 --- a/source/lib/predicates/predicate.ts +++ b/source/lib/predicates/predicate.ts @@ -70,9 +70,13 @@ export class Predicate implements BasePredicate { // 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; } diff --git a/source/test/optional.ts b/source/test/optional.ts index 8ae5563..fe56da3 100644 --- a/source/test/optional.ts +++ b/source/test/optional.ts @@ -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`');