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

Help about zod arrays and strings #3731

Open
marijuana-softwares-1 opened this issue Aug 29, 2024 · 1 comment
Open

Help about zod arrays and strings #3731

marijuana-softwares-1 opened this issue Aug 29, 2024 · 1 comment

Comments

@marijuana-softwares-1
Copy link

marijuana-softwares-1 commented Aug 29, 2024

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
Copy link

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.

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

2 participants