Replies: 4 comments 18 replies
-
You have a few choices, but it depends on what those conditions are. In all things, it's best to be as truthful to the schema as you can, which sometimes requires multiple schemas or some duplication. Other than const fooSchema = z.object({
bar: z.string().min(1),
baz: z.string().min(1),
});
const bazSchema = z.object({
bar: z.literal(""),
baz: z.literal(""),
});
const schema = z.union([fooSchema, bazSchema]);
schema.safeParse({ bar: "not empty", baz: "" }); // failure
schema.safeParse({ bar: "", baz: "" }); // success
schema.safeParse({ bar: "not empty", baz: "not empty also" }); // success It might help to provide some simple examples of what problem you're trying to model. |
Beta Was this translation helpful? Give feedback.
-
There might be other ways to do this, but I feel like Here's a simple example of how to use refine for this. const myString = z.object( {
foo: z.string(),
// must be optional or parse will fail before refinement is applied
bar: z.string().optional(),
} ).refine( input => {
// allows bar to be optional only when foo is 'foo'
if ( input.foo !== 'foo' && input.bar === undefined ) return false
return true
} )
// bar is optional here
console.log( myString.safeParse( { foo: 'foo' } ).success ) // true
console.log( myString.safeParse( { foo: 'foo', bar: 'bar' } ).success ) // true
console.log( myString.safeParse( { foo: 'foo', bar: undefined } ).success ) // true
// bar is required here
console.log( myString.safeParse( { foo: 'not foo', bar: 'bar' } ).success ) // true
console.log( myString.safeParse( { foo: 'not foo' } ).success ) // false
console.log( myString.safeParse( { foo: 'not foo', bar: undefined } ).success ) // false |
Beta Was this translation helpful? Give feedback.
-
There is also #1394 now |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
I have a situation where I need to conditionally require another field based on the validity of another field. AFAIK, we can only enforce this by using
refine
orsuperRefine
. The enforcement however only comes to fruition through the use ofaddIssue(...)
. Is there a way to actually set a field as arequired
oroptional
or is that basically whatrefine
/superRefine
does under the hood?Beta Was this translation helpful? Give feedback.
All reactions