diff --git a/source/predicates/string.ts b/source/predicates/string.ts index 22fb23d..ab3f7c3 100644 --- a/source/predicates/string.ts +++ b/source/predicates/string.ts @@ -1,3 +1,4 @@ +import is from '@sindresorhus/is'; import valiDate from 'vali-date'; import {Predicate, PredicateOptions} from './predicate'; @@ -205,4 +206,14 @@ export class StringPredicate extends Predicate { validator: value => value.trim() !== '' && value === value.toUpperCase() }); } + + /** + * Test a string to be a valid URL. + */ + get url() { + return this.addValidator({ + message: (value, label) => `Expected ${label} to be a URL, got \`${value}\``, + validator: is.urlString + }); + } } diff --git a/test/string.ts b/test/string.ts index c55e015..fdb9d2c 100644 --- a/test/string.ts +++ b/test/string.ts @@ -310,3 +310,21 @@ test('string.uppercase', t => { ow('', ow.string.uppercase); }, 'Expected string to be uppercase, got ``'); }); + +test('string.url', t => { + t.notThrows(() => { + ow('https://sindresorhus.com', ow.string.url); + }); + + t.notThrows(() => { + ow('file:///path/to/an/awesome/file', ow.string.url); + }); + + t.throws(() => { + ow('foo' as any, ow.string.url); + }, 'Expected string to be a URL, got `foo`'); + + t.throws(() => { + ow('foo' as any, 'bar', ow.string.url); + }, 'Expected string `bar` to be a URL, got `foo`'); +});