fix: bug that accepted 3 digit year (#2489)

* fix: bug that accepted 3 digit year

* fix: bug that accepted 3 digit year

* Update packages/ui/components/localize/test/date/parseDate.test.js

---------

Co-authored-by: Thijs Louisse <t_louisse@hotmail.com>
This commit is contained in:
Sebastian Kamiński 2025-03-13 08:34:56 +01:00 committed by GitHub
parent 593b753f0f
commit a181a035e9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 25 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'@lion/ui': patch
---
[localize] Fix bug that accepted 3 digit year

View file

@ -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 &&

View file

@ -0,0 +1,8 @@
/**
*
* @param {string} year
* @returns {boolean}
*/
export function isCorrectYearFormat(year) {
return /^\d{2}(\d{2})?$/g.test(year);
}

View file

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