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(); }