From f8197836e46960d3a8800192cf13575b373afd77 Mon Sep 17 00:00:00 2001 From: Valerii Sidorenko Date: Wed, 30 Oct 2024 10:41:55 +0100 Subject: [PATCH] fix: isValid should not throw (#78) --- src/parser/parser.test.ts | 4 +++- src/parser/parser.ts | 27 +++++++++++++++++---------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/parser/parser.test.ts b/src/parser/parser.test.ts index bfedf59..e36bc04 100644 --- a/src/parser/parser.test.ts +++ b/src/parser/parser.test.ts @@ -104,8 +104,10 @@ describe('custom parser', () => { }); describe('isValid', () => { - it('should return false when invalid date text', () => { + it('should return false on invalid input', () => { expect(isValid('asd')).toBe(false); + // @ts-expect-error + expect(isValid({invalid: true})).toBe(false); }); it('should return true when valid date text', () => { expect(isValid('now-1h')).toBe(true); diff --git a/src/parser/parser.ts b/src/parser/parser.ts index 0b4c9c4..6c5f4cd 100644 --- a/src/parser/parser.ts +++ b/src/parser/parser.ts @@ -25,9 +25,12 @@ const parseInput: DateTimeParser = ( } const {format, lang} = options || {}; - const date = dateTime({input, format, lang, timeZone: options?.timeZone}); - - return date.isValid() ? date : undefined; + try { + const date = dateTime({input, format, lang, timeZone: options?.timeZone}); + return date.isValid() ? date : undefined; + } catch { + return undefined; + } }; /** @@ -61,15 +64,19 @@ export const dateTimeParse: DateTimeParser = ( * @param value value to parse. */ export function isValid(value?: string | DateTime): boolean { - if (isDateTime(value)) { - return value.isValid(); - } + try { + if (isDateTime(value)) { + return value.isValid(); + } + + const date = dateTimeParse(value, {allowRelative: true}); - const date = dateTimeParse(value, {allowRelative: true}); + if (!date) { + return false; + } - if (!date) { + return date.isValid(); + } catch { return false; } - - return date.isValid(); }