ui/form_state.svelte.ts

Reactive form state for controlling when field errors appear and focusing invalid fields.

Tracks per-field touched state (set on blur via delegated focusout) and form-level attempted state (set on submit attempt). Errors show after a field is blurred or after a submit attempt, avoiding premature validation while the user is still typing.

The {@link FormState.form | form} attachment also handles Enter key advancing between focusable elements.

All trackable inputs must have a name attribute — an error is thrown in dev if an input without name loses focus.

@example

<script> const form_state = new FormState(); let username = $state(''); const username_valid = $derived(Username.safeParse(username).success); const can_submit = $derived(username.trim() && username_valid); const handle_submit = async () => { form_state.attempt(); if (!can_submit) { if (!username.trim() || !username_valid) form_state.focus('username'); return; } // submit... }; </script> <form {@attach form_state.form()} onsubmit={(e) => { e.preventDefault(); void handle_submit(); }}> <input name="username" bind:value={username} /> {#if form_state.show('username') && username && !username_valid} <p>error message</p> {/if} <PendingButton onclick={handle_submit}>submit</PendingButton> </form>

Declarations
#

view source

FormState
#

ui/form_state.svelte.ts view source

form

Creates a form attachment that handles Enter key advancing between focusable elements and tracks field touched state via delegated focusout.

Fields are identified by their name attribute.

type (): Attachment<HTMLFormElement>

returns Attachment<HTMLFormElement>

is_touched

Whether a field has been blurred at least once.

type (field: string): boolean

field
type string
returns boolean

show

Whether to show validation errors for a field. Returns true if the field has been blurred or a submit attempt was made.

type (field: string): boolean

field
type string
returns boolean

touch

Programmatically marks a field as touched without requiring a blur event.

type (field: string): void

field
type string
returns void

focus

Focuses the named input within the form.

type (field: string): void

field
type string
returns void

attempt

Marks the form as having been submitted, causing all field errors to show.

type (): void

returns void

reset

Resets all touched and attempted state.

type (): void

returns void

Imported by
#