Skip to content

Instantly share code, notes, and snippets.

@ciscoheat
Created May 21, 2023 19:11
Show Gist options
  • Save ciscoheat/8e9935bf7fe8a023bd8b93f07202441d to your computer and use it in GitHub Desktop.
Save ciscoheat/8e9935bf7fe8a023bd8b93f07202441d to your computer and use it in GitHub Desktop.
Checkbox validation test for Superforms
import type { Actions, PageServerLoad } from './$types';
import { superValidate } from 'sveltekit-superforms/server';
import { schema } from './schemas';
export const load = (async () => {
const form = await superValidate(schema);
return { form };
}) satisfies PageServerLoad;
export const actions = {
default: async ({ request }) => {
const formData = await request.formData();
const form = await superValidate(formData, schema);
console.log('POST', form);
return { form };
}
} satisfies Actions;
<script lang="ts">
import { superForm } from 'sveltekit-superforms/client';
import type { PageData } from './$types';
import SuperDebug from 'sveltekit-superforms/client/SuperDebug.svelte';
import { schema } from './schemas';
import Checkbox from './Checkbox.svelte';
export let data: PageData;
const { form, errors, tainted, enhance } = superForm(data.form, {
validators: schema,
validationMethod: 'oninput'
});
</script>
<SuperDebug data={{ $form, $errors, $tainted }} />
<form method="POST" use:enhance>
<Checkbox
name="isAccredited"
label="I confirm that I am an accredited investor"
bind:checked={$form.isAccredited}
/>
{#if $errors.isAccredited}<span class="invalid"
>{$errors.isAccredited}</span
>{/if}
<div>
<button>Submit</button>
</div>
</form>
<style lang="scss">
form {
margin: 2rem 0;
}
.invalid {
color: red;
}
</style>
<script lang="ts">
export let label: string;
export let name: string;
export let checked: boolean;
</script>
<input type="checkbox" {name} bind:checked /> <span>{label}</span>
import { z } from 'zod';
export const schema = z.object({
isAccredited: z.literal(true)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment