From 2c41fab146ff4265be78a977c898349d88d24fe8 Mon Sep 17 00:00:00 2001 From: Cecilia Sanare Date: Fri, 27 Oct 2023 14:42:10 -0500 Subject: [PATCH] fix: ignore nested object validation if the parent object does not exist --- src/__tests__/index.spec.ts | 34 ++++++++++++++++++++++++++++++++-- src/index.ts | 2 +- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/__tests__/index.spec.ts b/src/__tests__/index.spec.ts index 3f5114e..0359a82 100644 --- a/src/__tests__/index.spec.ts +++ b/src/__tests__/index.spec.ts @@ -29,7 +29,11 @@ describe('class(Validator)', () => { }, }); - expect(validator.check({})).toEqual(['"messages.hello" is not defined']); + expect( + validator.check({ + messages: {}, + }) + ).toEqual(['"messages.hello" is not defined']); }); it('should support any number of nested objects', () => { @@ -49,7 +53,33 @@ describe('class(Validator)', () => { }, }); - expect(validator.check({})).toEqual(['"i18n.en.hello" is not defined']); + expect( + validator.check({ + i18n: { + en: {}, + }, + }) + ).toEqual(['"i18n.en.hello" is not defined']); + }); + + it('should ignore validation if a parent object does not exist', () => { + type Example = { + i18n: { + en: { + hello: string; + }; + }; + }; + + const validator = new Validator({ + i18n: { + en: { + hello: [isDefined], + }, + }, + }); + + expect(validator.check({})).toEqual([]); }); it('should support ensuring arrays exist', () => { diff --git a/src/index.ts b/src/index.ts index e03c71f..23e8f46 100644 --- a/src/index.ts +++ b/src/index.ts @@ -50,7 +50,7 @@ export class Validator { config: configItem, }); } - } else { + } else if (innerValue) { stack.push({ parentKey: innerKey, item: innerValue,