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

Handle checkboxes with Zod? #107

Closed
kentcdodds opened this issue Mar 7, 2023 · 10 comments
Closed

Handle checkboxes with Zod? #107

kentcdodds opened this issue Mar 7, 2023 · 10 comments

Comments

@kentcdodds
Copy link
Contributor

Does conform do anything to coerce a checkbox to a boolean when using a Zod schema?

@brandonpittman
Copy link
Contributor

brandonpittman commented Mar 7, 2023

I don't believe so. I borrowed zod-form-data's .checkbox method.

https://github.com/airjp73/remix-validated-form/blob/f430df7c2ee743bc2017831892afca5472f30f35/packages/zod-form-data/src/helpers.ts#L79-L83

@edmundhung
Copy link
Owner

Conform does not coerce anything as there is no easy way to determine if the form data was set with a checkbox from the server.

You can set it up as z.string().transform(value => value === 'on') or z.preprocess(value => value === 'on', z.boolean()) based on your preference.

@edmundhung
Copy link
Owner

You can now use z.boolean() for required checkbox and z.boolean().optional() for optional checkbox from v0.8.0.

@kentcdodds
Copy link
Contributor Author

Sweet!

@luanfonsecap
Copy link

How can i validate if at least one checkbox is checked? Any suggestions?

@edmundhung
Copy link
Owner

@luanfonsecap It sounds like you are validating a list of checkboxes. In this case I will define a string array schema with a nonEmpty check.

@binajmen
Copy link

@luanfonsecap It sounds like you are validating a list of checkboxes. In this case I will define a string array schema with a nonEmpty check.

But if you only select one checkbox, it becomes a string instead of an array of one value 🤔

@edmundhung
Copy link
Owner

Yep. It will be a string instead of an array of there is only 1 item. But it should work fine because of the automatic type coercion feature with zod which will transform it to an array before validating it.

@timzolleis
Copy link

Is there an option to use z.boolean inside nested objects? Lets say I have:

const schema = z.object({
  entries: z.array(z.object({
    secret: z.boolean().optional()
  })
})

Which does not transform the checkboxes to booleans (even though they have the correct name) - im using it with "transform" right now. Is this a know bug or by design?

@edmundhung
Copy link
Owner

@timzolleis It might be related to #391 if you have no other text inputs inside the object.

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

6 participants