我在Zod模式中具有属性startDate和endDate。我想要证实的是:
也就是说,如果只设置了startDate或endDate,解析就会失败。
模式如下所示:
export const MediumSchema = z.object({
ImageSetID: z.number().int().positive(),
...
CampaignStartDate: z.date().nullable(),
CampaignEndDate: z.date().nullable(),
Url: z.string().url().transform((url) => new URL(url)),
CDNUrl: z.string().url().transform((url) => new URL(url))
});我怎样才能做到这一点?
发布于 2022-10-19 13:20:21
您可以使用union或内置or方法将您期望的两种可能的模式结合起来。例如:
import { z } from 'zod';
const schema = z.object({
startDate: z.date(),
endDate: z.date(),
});
const schemaBothUndefined = z.object({
startDate: z.undefined(),
endDate: z.undefined(),
});
const bothOrNeither = schema.or(schemaBothUndefined);
console.log(bothOrNeither.safeParse({})); // success
console.log(bothOrNeither.safeParse({
startDate: new Date(),
endDate: new Date(),
})); // success
console.log(bothOrNeither.safeParse({
startDate: new Date(),
})); // failure编辑:更大模式的一部分时的更多详细信息
如果要将模式用作更大模式的一部分,则可以对以下字段使用and:
import { z } from "zod";
const startAndEnd = z.object({
CampaignStartDate: z.date(),
CampaignEndDate: z.date(),
});
const neitherStartNorEnd = z.object({
CampaignStartDate: z.undefined(),
CampaignEndDate: z.undefined(),
});
const CampaignDates = startAndEnd.or(neitherStartNorEnd);
export const MediumSchema = z.object({
id: z.string(),
}).and(CampaignDates);
console.log(MediumSchema.safeParse({ id: '11' })); // success
console.log(MediumSchema.safeParse({
id: '11',
CampaignStartDate: new Date(),
CampaignEndDate: new Date()
})); // Success
console.log(MediumSchema.safeParse({
id: '11',
CampaignEndDate: new Date()
})); // Failurehttps://stackoverflow.com/questions/74122007
复制相似问题