Skip to content

Commit

Permalink
fix: isValid should not throw (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
ValeraS authored Oct 30, 2024
1 parent 73ebe01 commit f819783
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
4 changes: 3 additions & 1 deletion src/parser/parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
27 changes: 17 additions & 10 deletions src/parser/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@ const parseInput: DateTimeParser<DateTimeOptionsWhenParsing> = (
}

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

/**
Expand Down Expand Up @@ -61,15 +64,19 @@ export const dateTimeParse: DateTimeParser<DateTimeOptionsWhenParsing> = (
* @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();
}

0 comments on commit f819783

Please sign in to comment.