我正在使用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>;
是否有一种方法来添加验证到datetime抛出错误,如果datetime提交大于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
有点晚了,但万一有人更喜欢不干涉的方式
const utcCheck = (kind: "min" | "max", offset = 0) => ({
kind: kind,
get value() {
return Date.now() + offset;
}
});
使用
zod.date()._addCheck(utcCheck("max"))