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

[getZodConstraint] Required fields in discriminatedUnion are false #683

Open
dkAndFed opened this issue Jun 17, 2024 · 3 comments
Open

[getZodConstraint] Required fields in discriminatedUnion are false #683

dkAndFed opened this issue Jun 17, 2024 · 3 comments

Comments

@dkAndFed
Copy link

dkAndFed commented Jun 17, 2024

Describe the bug and the expected behavior

Unsure if this is an error in implementation or it's intentional (unsure why though), but using getZodConstraint with z.discriminatedUnion the fields are always set to as false on required although they are required by the schema.

Conform version

v1.1.4

Steps to Reproduce the Bug or Issue

const s = z.discriminatedUnion('a', [
  z.object({
    a: z.literal('1'),
    b: z.string(), // b should be required
    z: z.object({ // z should be required
      u: z.string(), // z.u should be required
      y: z.string().optional(),
    }),
  }),
  z.object({
    a: z.literal('2'),
    c: z.string(), // c should be required
  }),
]);

Output from getZodConstraint

{
  "a": {
    "required": true
  },
  "b": {
    "required": false // should be true
  },
  "z": {
    "required": false // should be true
  },
  "z.u": {
    "required": false // should be true
  },
  "z.y": {
    "required": false
  },
  "c": {
    "required": false // should be true
  }
}

What browsers are you seeing the problem on?

No response

Screenshots or Videos

No response

Additional context

The behavior seems to be caused by the following line of code; removing it resolves the issue and produces expected required values.

https://github.com/edmundhung/conform/blob/main/packages/conform-zod/constraint.ts#L90

@lifeiscontent
Copy link
Contributor

@dkAndFed I think you need a z.string().min(1) as outlined in the zod docs

@edmundhung
Copy link
Owner

It was intentional to keep only common properties as required. As it will make the form impossible to submit before JS loaded and it is too complex to update the constraint based on the current value.

@dkAndFed
Copy link
Author

@edmundhung Thanks for the explanation.

I suppose when using getZodConstraint directly with useForm, as intended, it makes sense what you are saying. My use however is without @conform-to/react as I am relying on a different form library and I only need to know which fields are required.

I suppose I could write my own function to parse the schema and infer which fields are required.

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

3 participants