Browse Source

Check for optional first before running validator (#125)

string-allowed-chars
Sam Verschueren 6 years ago
committed by Sindre Sorhus
parent
commit
3de78add9e
  1. 6
      source/lib/predicates/predicate.ts
  2. 1
      source/test/optional.ts

6
source/lib/predicates/predicate.ts

@ -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;
}

1
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`');

Loading…
Cancel
Save