React zodResolver put constraint date should be greater than now

Viewed 1126

I am using the zod library to validate my react forms. I am using this schema.

import * as zod from "zod";

export const appointmentSchema = zod.object({
  title: zod.string().nonempty("Please enter a title"),
  description: zod.string(),
  scheduledDate: zod.date()
});

export type appointmentFormData = zod.infer<typeof appointmentSchema>;

Is there a way to add validation to datetime to throw an error if datetime submitted is greater than date.now?

1 Answers

You should try like this :

import * as zod from "zod";

export const appointmentSchema = zod.object({
  title: zod.string().nonempty("Please enter a title"),
  description: zod.string(),
  scheduledDate: zod
  .instanceof(Date, { message: 'The Date field is required.' })
  .refine((date) => {
      return date < new Date(Date.now());
    }, "The date must be before today"),
});

export type appointmentFormData = zod.infer<typeof appointmentSchema>;

You will find the documentation of zod at the link below : https://github.com/colinhacks/zod

Related