Skip to content

Commit 091ed74

Browse files
committed
refactor(DatePicker, DateRangePicker): improve date parsing when users manually type in the input field
1 parent 96f6969 commit 091ed74

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

js/src/util/calendar.js

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,22 @@ const createDateOnly = groups => {
393393
return new Date(parsedYear, parsedMonth, parsedDay)
394394
}
395395

396+
/**
397+
* Helper function to determine expected parts count from patterns.
398+
* @param patterns - Array of date format patterns.
399+
* @returns Expected number of parts for a complete date.
400+
*/
401+
const getExpectedPartsCount = patterns => {
402+
if (patterns.length === 0) {
403+
return 3
404+
} // Default fallback
405+
406+
// Analyze the first pattern to determine expected parts count
407+
const firstPattern = patterns[0]
408+
const parts = firstPattern.split(/[-/.\s:]+/).filter(part => part.length > 0)
409+
return parts.length
410+
}
411+
396412
/**
397413
* Enhanced day parsing with locale-aware patterns.
398414
* @param dateString - The day string to parse.
@@ -407,25 +423,26 @@ const parseDayString = (dateString, locale, includeTime) => {
407423
if (!groups) {
408424
// Check if input looks like a complete date (has separators and multiple parts)
409425
// If so, use fallback parsing for formats like "2022/08/17", "2022-08-17"
410-
// If not (like "1", "12"), return null
426+
// If not (like "1", "12", "1/1"), return null
411427
const trimmed = dateString.trim()
412428
const hasDateSeparators = /[-/.:]/.test(trimmed)
413429
const parts = trimmed.split(/[-/.\s:]+/).filter(part => part.length > 0)
414-
const hasMultipleParts = parts.length >= 2
430+
const expectedPartsCount = getExpectedPartsCount(patterns)
431+
const hasRequiredParts = parts.length >= expectedPartsCount
415432

416-
if (hasDateSeparators && hasMultipleParts) {
433+
if (hasDateSeparators && hasRequiredParts) {
417434
// Use fallback for complete date strings that don't match locale patterns
418435
return parseLocalDateString(dateString)
419436
}
420437

421-
// For incomplete input like "1" or "12", return null
438+
// For incomplete input return null
422439
return null
423440
}
424441

425-
// For day selection, require at least month and day to be present
426-
if ("month" in groups && "day" in groups) {
427-
const { month, day } = groups
428-
if (!validateDateComponents(month, day)) {
442+
// For day selection, require at least year, month, and day to be present
443+
if ("year" in groups && "month" in groups && "day" in groups) {
444+
const { month, day, year } = groups
445+
if (!validateDateComponents(month, day, year)) {
429446
return null
430447
}
431448
} else {

0 commit comments

Comments
 (0)