Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: isValid should not throw #78

Merged
merged 1 commit into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}