Form

A native form that validates its fields and shows their errors.

Submit it empty or with one word to see the messages.

<script lang="ts">
  import { Button } from '#lib/components/ui/button';
  import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from '#lib/components/ui/field';

Installation

pnpm dlx @sveltery/ui@latest add form

Usage

<script lang="ts">
  import { Field, FieldError, FieldLabel } from '#lib/components/ui/field';
  import { Form, FormError } from '#lib/components/ui/form';
  import { Input } from '#lib/components/ui/input';
</script>
<Form method="POST">
  <Field name="email">
    <FieldLabel>Email</FieldLabel>
    <Input type="email" required />
    <FieldError />
  </Field>
  <FormError />
</Form>

Form is Sveltery Base's Form. It renders a <form> and leaves the browser's constraint validation on, so an invalid form never submits, with or without JavaScript. With JavaScript, it cancels the browser's bubble for each control inside a Field and shows the message in that field's FieldError instead.

Errors

Pass errors to show errors from a server or a validation library, keyed by field name. Each Field shows the entry under its name, and editing the field hides it. A message under the empty key '' belongs to the whole form, and FormError shows it.

<Form {errors} values={submitted}>
  <!-- Fields -->
  <FormError />
</Form>

values fills each control by name, so a form that comes back from the server keeps what the user typed.

Remote forms

Pass a SvelteKit remote form as form. Form takes its method, action and submit handling, each Field reads its issues by its name, and FormError shows the issues that belong to no field. See Remote forms.

<Form form={signup}>
  <Field name="email">
    <FieldLabel>Email</FieldLabel>
    <Input {...signup.fields.email.as('email')} required />
    <FieldError />
  </Field>
  <FormError />
</Form>

Submitting

onsubmit runs only after every constraint passes. Read the values with FormData:

<Form
  onsubmit={(event) => {
    event.preventDefault();
    save(Object.fromEntries(new FormData(event.currentTarget)));
  }}
>
  <!-- Fields -->
</Form>

API Reference

Form

It takes every Form prop and every <form> attribute.

PropTypeDefault
forma SvelteKit remote form
errorsRecord<string, string \| string[]>
valuesRecord<string, unknown>
validationMode"onSubmit" | "onBlur" | "onChange""onSubmit"
validationDebounceTimenumber0
classstring

FormError

Shows the messages that belong to no field: a remote form's invalid('message'), or the errors entry under ''. One message renders as text and several as a list. It renders nothing without messages.

PropTypeDefault
matchboolean
childrenSnippet | Snippet<[messages: string[]]>
classstring