diff --git a/.changeset/new-cobras-sort.md b/.changeset/new-cobras-sort.md new file mode 100644 index 000000000..49bb32df9 --- /dev/null +++ b/.changeset/new-cobras-sort.md @@ -0,0 +1,5 @@ +--- +'@lion/ui': patch +--- + +[localize] Fix bug that accepted 3 digit year diff --git a/packages/ui/components/localize/src/date/parseDate.js b/packages/ui/components/localize/src/date/parseDate.js index 671c19309..8a3fccf50 100644 --- a/packages/ui/components/localize/src/date/parseDate.js +++ b/packages/ui/components/localize/src/date/parseDate.js @@ -1,6 +1,7 @@ import { getDateFormatBasedOnLocale } from './getDateFormatBasedOnLocale.js'; import { getLocalizeManager } from '../getLocalizeManager.js'; import { addLeadingZero } from './utils/addLeadingZero.js'; +import { isCorrectYearFormat } from './utils/checkYearFormat.js'; /** * @typedef {import('../../types/LocalizeMixinTypes.js').FormatDateOptions} FormatDateOptions @@ -63,12 +64,16 @@ export function parseDate(dateString, options) { } const [year, month, day] = parsedString.split('/').map(Number); + const [yearString] = parsedString.split('/'); + if (!isCorrectYearFormat(yearString)) { + return undefined; + } let correctedYear = year; if (year < 50) { correctedYear = 2000 + year; } - const parsedDate = new Date(new Date(correctedYear, month - 1, day)); + const parsedDate = new Date(correctedYear, month - 1, day); // Check if parsedDate is not `Invalid Date` or that the date has changed (e.g. the not existing 31.02.2020) if ( year > 0 && diff --git a/packages/ui/components/localize/src/date/utils/checkYearFormat.js b/packages/ui/components/localize/src/date/utils/checkYearFormat.js new file mode 100644 index 000000000..c1aa14027 --- /dev/null +++ b/packages/ui/components/localize/src/date/utils/checkYearFormat.js @@ -0,0 +1,8 @@ +/** + * + * @param {string} year + * @returns {boolean} + */ +export function isCorrectYearFormat(year) { + return /^\d{2}(\d{2})?$/g.test(year); +} diff --git a/packages/ui/components/localize/test/date/parseDate.test.js b/packages/ui/components/localize/test/date/parseDate.test.js index a42f62179..0516f1ebd 100644 --- a/packages/ui/components/localize/test/date/parseDate.test.js +++ b/packages/ui/components/localize/test/date/parseDate.test.js @@ -91,4 +91,10 @@ describe('parseDate()', () => { expect(parseDate('02.31.2020')).to.equal(undefined); // non existing date expect(parseDate('31.12.2020')).to.equal(undefined); // day & month switched places }); + + it('returns undefined for incorrect year format', () => { + // TODO: we need a `> 0` check for day and month, but maybe consider `>= 0` for year? + expect(parseDate('12-12-0000')).to.equal(undefined); + expect(parseDate('12-12-999')).to.equal(undefined); + }); });