-
-
Notifications
You must be signed in to change notification settings - Fork 94
Input component example
Andreas Söderlund edited this page Mar 30, 2023
·
5 revisions
src/routes/+page.svelte
<script lang="ts">
const { fields, enhance, delayed } = superForm(data.form);
</script>
<form method="POST" use:enhance>
<Input label="Name" field={fields.name} />
<Input label="E-mail" field={fields.email} />
<div>
<button>Submit</button> {#if $delayed}Working...{/if}
</div>
</form>
Input.svelte
<script lang="ts">
import type { FormField } from 'sveltekit-superforms';
type T = $$Generic<AnyZodObject>;
type P = $$Generic<keyof z.infer<T>>;
export let type = 'text';
export let label: string;
export let field: FormField<T, P>;
export let placeholder = '';
function setType(el: HTMLInputElement) {
el.type = type;
}
$: value = field.value;
$: errors = field.errors;
$: constraints = field.constraints;
</script>
<label>
{label}<br /><input
use:setType
{placeholder}
bind:value={$value}
name={field.name}
{...$constraints}
data-invalid={$errors}
/>
{#if $errors}<span class="invalid">{$errors}</span>{/if}
</label>
<style lang="scss">
[data-invalid],
.invalid {
color: red;
}
</style>