Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object Field: optional objects not working #160

Open
adityacodepublic opened this issue Mar 19, 2025 · 1 comment
Open

Object Field: optional objects not working #160

adityacodepublic opened this issue Mar 19, 2025 · 1 comment

Comments

@adityacodepublic
Copy link
Contributor

In the current implementation

  • 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.
const arrayTest = z.object({
  req_optional: z.array(z.string().min(2).optional()).nonempty(), // req out optional inside

  req_req: z.array(z.string().min(2)).nonempty(), // req out req inside

  optional_req: z.array(z.string().min(2)).optional(), // optional out req inside

  optional_optional: z.array(z.string().min(2).optional()).optional(), // optional out optional inside
});

const objTest = 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.
@adityacodepublic
Copy link
Contributor Author

adityacodepublic commented Mar 19, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant