sveltekit-superforms icon indicating copy to clipboard operation
sveltekit-superforms copied to clipboard

boolean default value set to `true` in schema defaults to `false` when validating URL

Open OTheNonE opened this issue 3 months ago • 3 comments

  • [X] Before posting an issue, read the FAQ and search the previous issues.

Description Basically the title of the issue:

const formSchema = z.object({
    "orderby": z.boolean().default(true), // Set default value of `orderby` to `true`
});

const url = new URL("http://test.com") // create an `URL` with no `searchParams` set.

const form = await superValidate(url, zod(formSchema)) // URL validation.

console.log(form.data.orderby) // returns `false`

MRE: https://www.sveltelab.dev/ivgtl6o005nlof3

OTheNonE avatar Aug 20 '25 19:08 OTheNonE

A few observations here:

  1. This seems to be intended: https://github.com/ciscoheat/sveltekit-superforms/blob/0880f91fef0473ead2a4a690699860bf8847ee5d/src/lib/formData.ts#L320-L323 (at least this code is the root cause of the value being set to false if the orderby member is undefined (i.e. not set in the URL at all) or '' (i.e. set to ?orderby= in the URL)).
  2. This does not occur when using Zod 4 instead of Zod 3, because the Zod 4 JSONSchema conversion lists orderby as being a required value whereas the Zod 3 JSONSchema conversion makes orderby implicitly optional, therefor triggering the above code segment.

kaechele avatar Oct 07 '25 04:10 kaechele

Thank you both for looking into this, the complications arise from the standard HTML behavior for checkboxes, which simply doesn't exist in the FormData if posted unchecked. And as checkboxes are boolean, this workaround was created.

As a fix, I'm going to differ between FormData and URL for the next release. It complicates things even further unfortunately, but the observed behavior in this issue doesn't make sense, so something has to be done.

ciscoheat avatar Oct 17 '25 12:10 ciscoheat

Now in 2.28.0, URL parsing should not return false anymore. Please check if it works fine!

ciscoheat avatar Oct 19 '25 04:10 ciscoheat