Skip to content

Commit f1e0c08

Browse files
author
Kubit
committed
Improve syntheticDate elements and utilities
1 parent e287ce4 commit f1e0c08

File tree

3 files changed

+21
-6
lines changed

3 files changed

+21
-6
lines changed

src/utils/syntheticComponents/__tests__/syntheticDate.test.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,23 @@ describe('syntheticDate test', () => {
1515
const date = '11-02-2020';
1616
const format = 'DD-MM-YYYY';
1717

18-
const rightFormatDate = formatDateToNative(date, format);
18+
const rightFormatDate = formatDateToNative(date, format, false);
1919

2020
expect(rightFormatDate).toBe('2020-02-11');
2121
});
22-
it('fill in the year with zeros when it is less than four digits', () => {
22+
it('empty date when it doesnt comply with valid format', () => {
23+
const date = '2024-09-1';
24+
const format = 'YYYY-MM-DD';
25+
26+
const rightFormatDate = formatDateToNative(date, format, false);
27+
28+
expect(rightFormatDate).toBe('');
29+
});
30+
it('fill in the year with zeros when year is in the last position and value is less than four digits', () => {
2331
const date = '11-02-2';
2432
const format = 'DD-MM-YYYY';
2533

26-
const rightFormatDate = formatDateToNative(date, format);
34+
const rightFormatDate = formatDateToNative(date, format, false);
2735

2836
expect(rightFormatDate).toBe('0002-02-11');
2937
});

src/utils/syntheticComponents/syntheticDate/helper/formatDateToNative.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1+
import { splitDate } from '@/components/inputDate/utils/verifyDate';
2+
13
const DD = 'DD';
24
const MM = 'MM';
35
const YYYY = 'YYYY';
46

5-
export const formatDateToNative = (value: string, format: string): string => {
6-
if (value.length > 5) {
7+
export const formatDateToNative = (value: string, format: string, hasRange: boolean): string => {
8+
const { dateToCheck } = splitDate(value, format, '', hasRange);
9+
10+
// Check if year is the last position in the format to trigger zeros autocomplete
11+
const isYearLastPosition = format.slice(-4) === 'YYYY' && value.length > 5;
12+
13+
if (isYearLastPosition || dateToCheck) {
714
const regex = /[a-zA-Z0-9\s]/g;
815
const symbol = format.replace(regex, '').split('')[0];
916

src/utils/syntheticComponents/syntheticDate/syntheticDate.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export const syntheticDate = (name?: string): ReturnValue => {
2020
});
2121

2222
const setDate = (value: string, format: string) => {
23-
const validDate = formatDateToNative(value, format);
23+
const validDate = formatDateToNative(value, format, false);
2424

2525
dateElement.value = validDate;
2626
dateElement.dispatchEvent(changeEvent);

0 commit comments

Comments
 (0)