Skip to content

Object Field: optional objects not working #160

Description

@adityacodepublic

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions