Skip to content
Open
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
69 changes: 61 additions & 8 deletions app/routes/events/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,67 @@ export const action: ActionFunction = async ({ request }) => {
return redirect(`/events/${createdEvent.id}`)
} catch (e) {
if (e instanceof ZodError) {
const errors = e.format()
return json<ActionData>(
{
data,
errors,
},
{ status: 422 }
)
const dateIsTodayOrInTheFuture = () => {
const dateFromForm = new Date(data.date.toString())
const today = new Date()
today.setHours(0, 0, 0, 0)
return dateFromForm >= today
}

const dateIsTodayAndTimeIsInPast = () => {
const timeFromForm = new Date(`${data.date}T${data.time}${data.timezone || 'Z'}` as string)
const today = new Date()
const isToday = new Date(data.date.toString()).getDate() === today.getDate()
return isToday && timeFromForm < today
}

const timeIsSubmitted = data.time !== ''
const dateIsValid = data.date !== '' && dateIsTodayOrInTheFuture()
const dateIsValidButTimeIsNotSubmitted = dateIsValid && !timeIsSubmitted
const dateIsValidButTimeIsInThePast =
timeIsSubmitted && data.date !== '' && dateIsTodayAndTimeIsInPast()

const errors: { [key: string]: string[] | { _errors: string[] } } = e.format()

if (dateIsValidButTimeIsNotSubmitted) {
delete errors.date
errors.time = { _errors: ['Invalid time. Time is required'] }

return json<ActionData>(
{
data,
errors,
},
{ status: 422 }
)
}

if (dateIsValidButTimeIsInThePast) {
delete errors.date
errors.time = {
_errors: ['Invalid time. Ensure the time is set in the future, or change the date'],
}

return json<ActionData>(
{
data,
errors,
},
{ status: 422 }
)
} else {
if (errors.time) {
errors.time = { _errors: ['Invalid time'] }
}

return json<ActionData>(
{
data,
errors,
},
{ status: 422 }
)
}
}
}
}
Expand Down