基于另一个字段的ZOD验证

huangapple go评论60阅读模式
英文:

ZOD validation based on another field

问题

如果 field1field2 都为空 - 不合法

如果 field1field2 都不为空 - 不合法

其他情况都合法。

英文:

Imagine I have an object like

{
  field1: 'test',
  field2: 'test1'
}

How I can create the following validation:

If field1 and field2 both are empty - it is not valid

If field1 and field2 both are not empty - it is not valid

Other cases are valid.

答案1

得分: 18

you can use .refine()

const res = z.object({
    field1: z.string().optional(),
    field2: z.string().optional(),
}) 
.refine(schema => (schema.field1 === undefined && schema.field2 === undefined 
    || schema.field2 !== undefined && schema.field1 !== undefined) ? false : true, 
{
    message: 'your message'
})

more info here

英文:

you can use .refine()

const res = z.object({
field1: z.string().optional(),
field2: z.string().optional(),
}) 
.refine(schema => (schema.field1===undefined && schema.field2===undefined 
|| schema.field2!==undefined && schema.field1!==undefined) ? false :true, 
{
message: 'your message'
})

more info here

huangapple
  • 本文由 发表于 2023年2月26日 21:03:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572170.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定