diff --git a/app/routes/events/new.tsx b/app/routes/events/new.tsx index 434de05..a819256 100644 --- a/app/routes/events/new.tsx +++ b/app/routes/events/new.tsx @@ -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( - { - 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( + { + 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( + { + data, + errors, + }, + { status: 422 } + ) + } else { + if (errors.time) { + errors.time = { _errors: ['Invalid time'] } + } + + return json( + { + data, + errors, + }, + { status: 422 } + ) + } } } }