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", "Phone is required",
"Please enter a valid phone number" "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({ address: z.object({
countryCode: z countryCode: z
.string({ .string({

View File

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