Zod 验证问题条件明智

问题描述 投票:0回答:1

默认显示电子邮件验证。如果将值添加到 contactNumber,则不需要电子邮件。但是,如果我们从联系号码中删除该值,则电子邮件将成为必需的。
当向联系号码字段添加值时,将电子邮件字段设置为可选;否则,请保留它。

vue.js vuejs3 zod shadcnui
1个回答
0
投票

您可以为此使用

union
类型

const base = z.object({
  other: z.string(),
  fields: z.string(),
  email: z.string(),
  contactNumber: z.string().optional()
})

const emailOptional = base.extend({
  email: z.string().optional(),
  contactNumber: z.string()
})

const schema = z.union([base, emailOptional])

type Schema = z.infer<typeof schema>
const test: Schema = {
  other: '',
  fields: '',
} // Email is required by default

const test2: Schema = {
  other: '',
  fields: '',
  contactNumber: ''
} // Email is optional when providing a contactNumber

© www.soinside.com 2019 - 2024. All rights reserved.