From 69a350c4da72a529fe6dbf83e3da3f9422492c14 Mon Sep 17 00:00:00 2001 From: Sebastian Seedorf Date: Wed, 27 May 2020 21:44:00 +0200 Subject: [PATCH] Added regex --- validators/string.test.ts | 33 ++++++++++++++++++++++++++++++++- validators/string.ts | 16 ++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/validators/string.test.ts b/validators/string.test.ts index 308cb22..4a2e14d 100644 --- a/validators/string.test.ts +++ b/validators/string.test.ts @@ -1,4 +1,4 @@ -import { isString, isUrl, isEmail } from "./string.ts"; +import { isString, isUrl, isEmail, fulfillsRegex } from "./string.ts"; import { validate } from "../mod.ts"; import { assertEquals, @@ -37,6 +37,8 @@ Deno.test("isString (no match)", async () => { Deno.test("isUrl (match)", async () => { const values = [ + undefined, + null, "http://google.com", "http://10.1.1.1", "http://10.1.1.254", @@ -70,8 +72,11 @@ Deno.test("isUrl (no match)", async () => { ); } }); + Deno.test("isEmail (match)", async () => { const values = [ + undefined, + null, "email@example.com", "firstname.lastname@example.com", "email@subdomain.example.com", @@ -116,3 +121,29 @@ Deno.test("isEmail (no match)", async () => { assertNotEquals(await validate(value, isEmail()), [], String(value)); } }); + +Deno.test("fulfillsRegex (match)", async () => { + const values: [any, RegExp][] = [ + ["abc", /[a-z]+/], + [null, /[a-z]+/], + [undefined, /[a-z]+/], + ["123abc", /[a-z]+/], + ["abc", /^[a-z]+$/], + ["^ab$", /^\^(ab)|(cd)\$$/] + ]; + for (const [value, regex] of values) { + assertEquals(await validate(value, fulfillsRegex({ regex })), [], `${String(value)} - ${regex}`); + } +}); + +Deno.test("fulfillsRegex (no match)", async () => { + const values: [any, RegExp][] = [ + [Symbol(), /[a-z]+/], + ["", /[a-z]+/], + ["abc123", /^[a-z]+$/], + ["^abcd$", /^\^(ab|cd)\$$/] + ]; + for (const [value, regex] of values) { + assertNotEquals(await validate(value, fulfillsRegex({ regex })), [], `${String(value)} - ${regex}`); + } +}); diff --git a/validators/string.ts b/validators/string.ts index 696ad46..986cc50 100644 --- a/validators/string.ts +++ b/validators/string.ts @@ -140,3 +140,19 @@ export function isEmail(): Validator { }, }; } + +export function fulfillsRegex({regex}: {regex: RegExp}): Validator { + return { + type: "fulfillsRegex", + extends: [isString()], + check: (value: any) => { + if (value === null || value === undefined) return; + if (!value.match(regex)) { + return {}; + } + }, + message: (value: any, args?: Args) => { + return `This value has to fulfill the regex ${regex}.`; + }, + }; +}