colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.8k stars 1.17k forks source link

Help about zod arrays and strings #3731

Open marijuana-softwares-1 opened 2 months ago

marijuana-softwares-1 commented 2 months ago

i am working on a simple project and i got stuck in working with zod arrays: currently i am pushing a zod string into the array then it works with the input element but the form won't submit bcz of the field and the field isn't validated.

export const formSchema = z.object({
        origins: z.array(z.string().min(1).max(256)
//      origins: z.string().array().min(1).max(256)
});
<script lang="ts">
    import { zodClient } from "sveltekit-superforms/adapters";
    import { superForm } from "sveltekit-superforms";
    import { formSchema } from "./schema.js";
    import { loadStore } from "$lib/store";
    import { z } from "zod";
    export let data;

    // HERE IS THE ISSUE SO PLS HLP
    function addOrigin() {
        if ($formData.origins.length >= 5) {
            toast.error("Reached the origins limit.", {
                action: {
                    label: "Close",
                    onClick: () => { return; }
                }
            })
            return;
        }

        $formData.origins.push(z.string().min(1).max(256)) // ONCE PUSHED THE FIELD SHOWS '[object Object]'
        $formData.origins = [...$formData.origins]
    }

    const form = superForm(data.form, {
        validators: zodClient(formSchema),
    });
    const { form: formData, message, enhance } = form;
    $: if ($message) toast.error($message)

    addOrigin()
    $: for (let i = 0; i < $formData.origins.length; i += 1) {
        console.log($formData.origins[i])
    }
</script>

<form method="POST" use:enhance>
        <label>Origin</label>
        {#each $formData.origins as origin, index}
            <div class="flex w-full flex-row">
                <input type="text" placeholder="Http Origins" autofocus="1"bind:value={$formData.origins[index]} />
                <button on:click={remOrigin}>
                    Remove a Field
                </button>
            </div>
        {/each}
        <button on:click={addOrigin}>
            Add a Field
        </button>
        <button type="submit">Continue</button>
</form>
sunnylost commented 2 months ago

Uh, If I understand correctly, there seems to be a misunderstanding. Zod is used to generate schemas. The $formData.origins requires actual data, while a schema is used to validate that data. A schema itself cannot be treated as data, so it's important not to mix these two concepts together.