Repository navigation
Replies: 1 comment
|
You can do this with a union, but each branch needs to describe both fields. In the original schema, Reuse the existing field validators and explicitly describe the empty values: export const useApplicationSchema = () => {
const comment = useCommentSchema().shape.comment;
const file = useFileSchema(MAX_FILE_SIZE); // required file validator, no .nullable()
const emptyComment = z.literal("").nullish(); // "", null, undefined, or omitted
return z.union([
z.object({
comment,
file: file.or(z.literal("")).nullish(),
}),
z.object({
comment: emptyComment,
file,
}),
]);
};The first branch requires a valid comment and allows a valid file or an empty file input. The second requires a valid file and an empty comment. Together they allow either field or both, while rejecting both-empty inputs. This assumes that a supplied, non-empty value must pass its own validator even when the other field is valid. I tested this composition on Zod 3.25.76 and 4.6.7, Node 24.22.1. Your
Whitespace isn't treated as empty by this example. It keeps your existing comment validation and error messages. Union errors have a different structure from a single object schema, so check how your form resolver displays the branch errors. Relevant docs: union evaluation, object key stripping, and nullish schemas. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hello
I wanna make a schema where at least 1 field is required. I know I can use refine but I think I can avoid it...
I've tried below a strategy but it's lacking. I've accomplished validating either one. But I am lacking a validation for when the user leaves BOTH empty. Any ideas?
The real complication is that the form consider null or empty string to be as EMPTY values. So, that's where I gotta pass these things through a truthy check to make sure there's a value in either one....
Would love some help :)
All reactions