Reference › APIs

On this page

clarusjs/forms

A headless forms engine. For the how-to with live forms, see Form validation.

ts
import { form } from 'clarusjs/forms'

form() #

ts
form<T>(values: Signal<T> | T, options?: FormOptions<T>): Form<T>

The engine for a form. Connect it to a <form> with [engine]="f". It validates the fields bound to values, using native constraints, a Standard Schema, and errors from the server. It shows each error on its field, and runs submit once everything is valid.

Parameters #

Returns #

A Form<T>:

Caveats #

Usage #

A form with server errors:

tscl
<script>
  import { form } from 'clarusjs/forms'
  let signup = state({ name: '', email: '' })
  const f = form(signup, {
    submit: async (values) => {
      const res = await fetch('/api/signup', { method: 'POST', body: JSON.stringify(values) })
      if (!res.ok) return { errors: await res.json() } // { "email": "Already registered" }
    },
  })
</script>

<form [engine]="f" novalidate>
  <label>Name <input required [(value)]="signup.name"> <small data-cl-message></small></label>
  <label>Email <input type="email" required [(value)]="signup.email"> <small data-cl-message></small></label>
  <button [disabled]="f.submitting">Sign up</button>
</form>

With a schema:

ts
import { z } from 'zod'
const f = form(signup, { schema: z.object({ name: z.string().min(2), email: z.string().email() }) })

Types #

FormError #

ts
type FormError<T> = { path: Path<T>; message: string; id: string; step: string | null }

An error being shown: its field's path, the message, the id of its message element (to link a summary to it) and its step.

tscl
<ul>@for (e of f.errors; track e.path) { <li><a href="#{{ e.id }}">{{ e.message }}</a></li> }</ul>

Path #

ts
type Path<T>

The dotted paths of a form's values, typed from T: 'customer.email', 'lines.0.item'. For values typed any, any string.

StandardSchema #

ts
type StandardSchema<T>

A Standard Schema: Zod, Valibot, ArkType and others implement it. clarusjs declares the type itself, so it doesn't depend on any of them.