Skip to content

feat: Add lenient validation of the date parsing #2873

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

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
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
27 changes: 25 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,19 @@ Utils.l = parseLocale
Utils.i = isDayjs
Utils.w = wrapper

const isLenient = (date, inputs) => {
if (
date.getFullYear() === Number(inputs.year) &&
date.getMonth() === Number(inputs.month) &&
date.getDate() === Number(inputs.day)
) {
return false
}
return true
}

const parseDate = (cfg) => {
const { date, utc } = cfg
const { date, utc, disallowLenient } = cfg
if (date === null) return new Date(NaN) // null is invalid
if (Utils.u(date)) return new Date() // today
if (date instanceof Date) return new Date(date)
Expand All @@ -74,8 +85,20 @@ const parseDate = (cfg) => {
return new Date(Date.UTC(d[1], m, d[3]
|| 1, d[4] || 0, d[5] || 0, d[6] || 0, ms))
}
return new Date(d[1], m, d[3]
const parsedDate = new Date(d[1], m, d[3]
|| 1, d[4] || 0, d[5] || 0, d[6] || 0, ms)
if (disallowLenient && isLenient(parsedDate, {
year: d[1],
month: m,
day: d[3] || 1,
hour: d[4] || 0,
minute: d[5] || 0,
second: d[6] || 0,
millisecond: ms
})) {
return new Date(NaN)
}
return parsedDate
}
}

Expand Down
23 changes: 23 additions & 0 deletions test/constructor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,26 @@ it('does not break isDayjs', () => {
expect(dayjs.isDayjs(dayjs())).toBeTruthy()
expect(dayjs.isDayjs(new Date())).toBeFalsy()
})

describe('disallowLenient configuration', () => {
it('isValid should return false for invalid days using default ISO format', () => {
const invalidDate = dayjs('2022-03-35T10:30:00', {
disallowLenient: true
})
expect(invalidDate.isValid()).toBeFalsy()
})

it('isValid should return false for invalid month using default ISO format', () => {
const invalidDate = dayjs('2022-13-20T10:30:00', {
disallowLenient: true
})
expect(invalidDate.isValid()).toBeFalsy()
})

it('isValid should return true for valid days using default ISO format', () => {
const validDate = dayjs('2022-03-25T10:30:00', {
disallowLenient: true
})
expect(validDate.isValid()).toBeTruthy()
})
})