我正在使用 zod 库来验证我的 react 表单。我正在使用这个架构。
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>;
有没有办法向日期时间添加验证,以便在提交的日期时间大于 date.now 时抛出错误?
最佳答案
你应该这样尝试:
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>;
您可以在以下链接找到 zod 的文档:https://github.com/colinhacks/zod
关于reactjs - React zodResolver放置约束日期应该大于现在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66275495/