From a4921e5aa1063a8fe5e2af6a45775e4e254c292d Mon Sep 17 00:00:00 2001 From: Henry Ing-Simmons Date: Fri, 7 Jun 2019 15:35:29 +0100 Subject: [PATCH] Making valid length validator pass for no value (#35) --- src/validators/valid-length.ts | 3 ++- test/validators/valid-length.test.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/validators/valid-length.ts b/src/validators/valid-length.ts index 16aadd4..701df65 100644 --- a/src/validators/valid-length.ts +++ b/src/validators/valid-length.ts @@ -32,7 +32,8 @@ export const validLength = (options: ValidLengthOptions) => { } return createValidator(s => - (options.min === undefined || s.length >= options.min) && (options.max === undefined || s.length <= options.max) + !s + || ((options.min === undefined || s.length >= options.min) && (options.max === undefined || s.length <= options.max)) , getMessage(options) ); }; diff --git a/test/validators/valid-length.test.ts b/test/validators/valid-length.test.ts index a6d768c..a2fbe18 100644 --- a/test/validators/valid-length.test.ts +++ b/test/validators/valid-length.test.ts @@ -5,6 +5,23 @@ import { validLength } from "../../src/validators/valid-length"; @TestFixture("ValidLength") export class ValidLengthTests { + @TestCase(null) + @TestCase(undefined) + @TestCase("") + @Test("should pass for null, undefined or empty") + public shouldPassForNullUndefinedOrEmpty(value: string) { + const message = "Invalid length"; + + const validator = validLength({ + min: 3, + max: 5, + message + }); + + const results = validator(value); + Expect(results).toBeAPass(); + } + @TestCase(2, 10, "12345") @TestCase(5, undefined, "12345") @TestCase(undefined, 6, "123")