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
Using checkboxes with zod is confusing #345
Comments
Definitely agree that the type coercion behaviour should be documented. Would you be interested in contributing? I think we can have a dedicated guide about type coercion. FYI, to set a default value with zod, you should use With regards to the behaviour, what you found is pretty much correct. This is mainly because I am happy to adjust the behaviour if we believe there is a better approach. Here is a few concerns I had if we default the value to
|
My bad with the Maybe this could just be a short chapter somewhere? Something like the following: Working with checkboxesCheckboxes only have an "on" state. Leaving them unchecked will result in the browser not sending any value for that field.
|
Actually forgot about default: |
I don't know what the deal is, but this doesn't work for me. When it is unchecked it indeed defaults to false. But when it is checked I get Expected boolean, received string. The only way I can get checkboxes to consistently work correctly is |
There is a test dedicated for this. So I would expect it to work. It could be a regression on zod 3.22. Maybe try downgrading your zod version to 3.21.4 and see if the issue is resolved. |
I will welcome a PR to add a tips here. Thanks! |
Under the assumption your check box state is either |
Describe the bug and the expected behavior
Checkboxes do not behave as expected.
If you use a checkbox with zod you get the following behaviour:
z.boolean()
– checking the checkbox is required. Unchecking it gives you a validation errorz.boolean().optional()
– checkbox not required, unchecking it gives youundefined
false
…z.boolean().optional().refine(v => v ?? false)
– Gives "Invalid input" during validationI realize that this might not be solvable in conform directly. In that case there should be some documentation for this IMO. This is a pretty common pattern, no?
Conform version
v0.9.1
Steps to Reproduce the Bug or Issue
https://codesandbox.io/p/sandbox/infallible-bhabha-h5sxxp?file=%2Fsrc%2FApp.tsx%3A31%2C36
What browsers are you seeing the problem on?
No response
Screenshots or Videos
No response
Additional context
No response
The text was updated successfully, but these errors were encountered: