You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We cannot define objects that are optional, but require inner fields if provided
This issue only occurs for objects, not arrays.
Example
// to make array required > use .nonempty() , else empty array passes validation.// to make array optional > use .optional() , to remove * required mark from field.constarrayTest=z.object({req_optional: z.array(z.string().min(2).optional()).nonempty(),// req out optional insidereq_req: z.array(z.string().min(2)).nonempty(),// req out req insideoptional_req: z.array(z.string().min(2)).optional(),// optional out req insideoptional_optional: z.array(z.string().min(2).optional()).optional(),// optional out optional inside});constobjTest=z.object({req_opt: z.object({names: z.string().min(2).optional(),age: z.coerce.number().optional(),}),opt_req: z.object({names: z.string(),age: z.coerce.number(),}).optional(),});
Issue
Arrays behave correctly with .optional() and .nonempty() for optional /required combinations.
Objects fail to handle the "optional object with required fields if present" case.
Example: opt_req enforce names and age even if the user dosen't want to provide it.
References
ObjectTest
objTest.mp4
ArrayTest
arrayTest.mp4
A possible use case
optional-req.mp4
Possible solutions
Render object fields on click like array field. (e.g., via a button or accordion).
This would keep the objects undefined to validation unless clicked by the user
--> enabling all req(optional) and optional(required), req(req), opti(opti) object fields.
The text was updated successfully, but these errors were encountered:
Note:
Rendering objects on click would also mean that users must open a Required(Optional inner fields) object even if they don't want to fill it, to submit the form.
In such cases, we could consider using Optional (Optional inner fields) instead.
In the current implementation
Example
Issue
References
ObjectTest
objTest.mp4
ArrayTest
arrayTest.mp4
A possible use case
optional-req.mp4
Possible solutions
--> enabling all req(optional) and optional(required), req(req), opti(opti) object fields.
The text was updated successfully, but these errors were encountered: