refactor(SW-649): reusable getDaysInMonth function

This commit is contained in:
Chuma McPhoy
2024-10-29 15:23:36 +01:00
parent 6a31aca0b1
commit 7ed2e1d5d0
2 changed files with 17 additions and 10 deletions

View File

@@ -16,7 +16,9 @@ export const signUpSchema = z.object({
"Phone is required",
"Please enter a valid phone number"
),
dateOfBirth: z.string().min(1),
dateOfBirth: z.string().min(1, {
message: "Date of birth is required",
}),
address: z.object({
countryCode: z
.string({

View File

@@ -56,15 +56,20 @@ export default function DateSelect({ name, registerOptions = {} }: DateProps) {
.reverse()
.map((year) => ({ value: year, label: year.toString() }))
const daysInMonth =
selectedMonth !== null && selectedYear !== null
? dt(`${selectedYear}-${selectedMonth + 1}-01`).daysInMonth()
: 31
function getDaysInMonth(year: number | null, month: number | null): number {
if (month === null) {
return 31
}
const yearToUse = year ?? new Date().getFullYear()
return dt(`${yearToUse}-${month + 1}-01`).daysInMonth()
}
const days = rangeArray(1, daysInMonth).map((day) => ({
value: day,
label: `${day}`,
}))
const days = rangeArray(1, getDaysInMonth(selectedYear, selectedMonth)).map(
(day) => ({
value: day,
label: `${day}`,
})
)
function handleSegmentChange(selector: DateName, value: number) {
let newYear = selectedYear
@@ -84,7 +89,7 @@ export default function DateSelect({ name, registerOptions = {} }: DateProps) {
newMonth = value - 1
setSelectedMonth(newMonth)
if (selectedDay) {
const maxDays = dt(`${newYear}-${value}-01`).daysInMonth()
const maxDays = getDaysInMonth(newYear, newMonth)
if (selectedDay > maxDays) {
newDay = maxDays
setSelectedDay(newDay)